Repair search and timeout defects
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / ExternalAccessRolesServiceImpl.java
1 package org.openecomp.portalapp.portal.service;
2
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.Iterator;
6 import java.util.LinkedHashMap;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Set;
10 import java.util.SortedSet;
11 import java.util.TreeSet;
12 import java.util.stream.Collectors;
13
14 import org.hibernate.Query;
15 import org.hibernate.Session;
16 import org.hibernate.SessionFactory;
17 import org.hibernate.Transaction;
18 import org.json.JSONArray;
19 import org.json.JSONObject;
20 import org.openecomp.portalapp.portal.domain.CentralRoleFunction;
21 import org.openecomp.portalapp.portal.domain.EPApp;
22 import org.openecomp.portalapp.portal.domain.EPAppRoleFunction;
23 import org.openecomp.portalapp.portal.domain.EPRole;
24 import org.openecomp.portalapp.portal.domain.EPUser;
25 import org.openecomp.portalapp.portal.domain.EPUserApp;
26 import org.openecomp.portalapp.portal.domain.ExternalRoleDetails;
27 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
28 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
29 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
30 import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction;
31 import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles;
32 import org.openecomp.portalapp.portal.transport.CentralApp;
33 import org.openecomp.portalapp.portal.transport.CentralRole;
34 import org.openecomp.portalapp.portal.transport.CentralUser;
35 import org.openecomp.portalapp.portal.transport.CentralUserApp;
36 import org.openecomp.portalapp.portal.transport.ExternalAccessPerms;
37 import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail;
38 import org.openecomp.portalapp.portal.transport.ExternalAccessRole;
39 import org.openecomp.portalapp.portal.transport.ExternalAccessRolePerms;
40 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
41 import org.openecomp.portalapp.portal.transport.ExternalRoleDescription;
42 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
43 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
44 import org.openecomp.portalapp.portal.utils.PortalConstants;
45 import org.openecomp.portalsdk.core.domain.Role;
46 import org.openecomp.portalsdk.core.domain.RoleFunction;
47 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
48 import org.openecomp.portalsdk.core.service.DataAccessService;
49 import org.openecomp.portalsdk.core.util.SystemProperties;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.context.annotation.EnableAspectJAutoProxy;
52 import org.springframework.http.HttpEntity;
53 import org.springframework.http.HttpHeaders;
54 import org.springframework.http.HttpMethod;
55 import org.springframework.http.ResponseEntity;
56 import org.springframework.stereotype.Service;
57 import org.springframework.transaction.annotation.Transactional;
58 import org.springframework.web.client.HttpClientErrorException;
59 import org.springframework.web.client.RestTemplate;
60
61 import com.fasterxml.jackson.core.JsonProcessingException;
62 import com.fasterxml.jackson.databind.DeserializationFeature;
63 import com.fasterxml.jackson.databind.ObjectMapper;
64 import com.fasterxml.jackson.databind.type.TypeFactory;
65
66 @Service("externalAccessRolesService")
67 @EnableAspectJAutoProxy
68 @EPMetricsLog
69 @EPAuditLog
70 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
71
72         private static final String IS_NULL_STRING = "null";
73
74         private static final String EXTERNAL_AUTH_PERMS = "perms";
75
76         private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
77
78         private static final String WHERE_APP_ID_EQUALS = " where app_id = ";
79
80         private static final String IS_EMPTY_JSON_STRING = "{}";
81
82         private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
83
84         private static final String WHERE_ROLE_ID_EQUALS = " where role_id = ";
85
86         private static final String APP_ROLE_ID = "appRoleId";
87
88         private static final String APP_ID = "appId";
89
90         private static final String PRIORITY = "priority";
91
92         private static final String ACTIVE = "active";
93
94         private static final String ROLE_NAME = "name";
95
96         private static final String ID = "id";
97
98         private static final String WHERE_ROLE_NAME_EQUALS = " where role_name = '";
99
100         private static final String APP_ID_EQUALS = " app_id = ";
101
102         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
103
104         @Autowired
105         private DataAccessService dataAccessService;
106
107         @Autowired
108         private SessionFactory sessionFactory;
109
110         RestTemplate template = new RestTemplate();
111
112         @SuppressWarnings("unchecked")
113         public List<EPRole> getAppRoles(Long appId) throws Exception {
114                 List<EPRole> applicationRoles = null;
115                 String filter = null;
116                 try {
117                         if (appId == 1) {
118                                 filter = " where app_id is null";
119                         } else {
120                                 filter = WHERE_APP_ID_EQUALS + appId;
121                         }
122                         applicationRoles = dataAccessService.getList(EPRole.class, filter, null, null);
123                 } catch (Exception e) {
124                         logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
125                         throw new Exception(e.getMessage());
126                 }
127                 return applicationRoles;
128         }
129
130         @SuppressWarnings("unchecked")
131         @Override
132         public List<EPApp> getApp(String uebkey) throws Exception {
133                 List<EPApp> app = null;
134                 try {
135                         app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null);
136                         if(!app.get(0).getEnabled()){
137                                 throw new Exception("Application:"+app.get(0).getName()+" is Unavailable");
138                         }
139                 } catch (Exception e) {
140                         logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
141                         throw new Exception(e.getMessage());
142                 }
143                 return app;
144         }
145
146         /**
147          * It returns  single application role from external auth system 
148          * @param addRole
149          * @param app
150          * @return JSON string which contains application role details
151          * @throws Exception
152          */
153         private String getSingleAppRole(String addRole, EPApp app) throws Exception {
154                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
155                 HttpEntity<String> entity = new HttpEntity<>(headers);
156                 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
157                 ResponseEntity<String> response = template
158                                 .exchange(
159                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
160                                                                 + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"),
161                                                 HttpMethod.GET, entity, String.class);
162                 logger.debug(EELFLoggerDelegate.debugLogger,
163                                 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ", response.getStatusCode().value());
164                 return response.getBody();
165         }
166
167         @Override
168         public boolean addRole(Role addRole, String uebkey) throws Exception {
169                 boolean response = false;
170                 ResponseEntity<String> addResponse = null;
171                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
172                 EPApp app = getApp(uebkey).get(0);
173                 String newRole = updateExistingRoleInExternalSystem(addRole, app);
174                 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
175                 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
176                 addResponse = template.exchange(
177                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
178                                 HttpMethod.POST, entity, String.class);
179                 if (addResponse.getStatusCode().value() == 201) {
180                         response = true;
181                         logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system  and response code: {} ", addResponse.getStatusCode().value());
182                 }
183                 if (addResponse.getStatusCode().value() == 406) {
184                         logger.error(EELFLoggerDelegate.errorLogger,
185                                         "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
186                 }
187                 return response;
188         }
189
190         /**
191          * 
192          * It deletes record in external auth system
193          * 
194          * @param delRole
195          * @return JSON String which has status code and response body 
196          * @throws Exception
197          */
198         private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
199                 ResponseEntity<String> delResponse = null;
200                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
201                 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
202                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
203                 delResponse = template.exchange(
204                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
205                                 HttpMethod.DELETE, entity, String.class);
206                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system and status code: {} ", delResponse.getStatusCode().value());
207                 return delResponse;
208         }
209
210         /**
211          * It updates role in external auth system
212          * 
213          * @param updateExtRole
214          * @param app
215          * @return true if success else false
216          * @throws Exception
217          *                                      If updateRoleInExternalSystem fails we catch it in logger for detail message
218          */
219         @SuppressWarnings("unchecked")
220         private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app) throws Exception {
221                 boolean response = false;
222                 ObjectMapper mapper = new ObjectMapper();
223                 ResponseEntity<String> deleteResponse = null;
224                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
225                 ExternalAccessRolePerms extRolePerms = null;
226                 ExternalAccessPerms extPerms = null;
227                 List<EPRole> epRoleList = null;
228                 epRoleList = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + updateExtRole.getId(), null, null);
229                 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
230                 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
231                         JSONObject jsonObj = new JSONObject(appRole);
232                         JSONArray extRole = jsonObj.getJSONArray("role");
233                         if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
234                                 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
235                                 Map<String, String> delRoleKeyMapper = new HashMap<>();
236                                 delRoleKeyMapper.put(ROLE_NAME, roleName);
237                                 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
238                                 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
239                                 if (deleteResponse.getStatusCode().value() != 200) {
240                                         throw new Exception(deleteResponse.getBody());
241                                 }
242                                 addRole(updateExtRole, app.getUebKey());
243                         } else {
244                                 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
245                                 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
246                                 List<ExternalAccessPerms> list = null;
247                                 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
248                                         JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
249                                         list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
250                                                         .constructCollectionType(List.class, ExternalAccessPerms.class));
251                                 }
252                                 ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class);
253                                 // If role name or role functions are updated then delete record in External System and add new record to avoid conflicts
254                                 Boolean existingRoleActive;
255                                 boolean isActiveValueChanged;
256                                 // check role active status
257                                 existingRoleActive = new Boolean(sysRoleList.getActive());
258                                 isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive());
259                                 if (!sysRoleList.getName().equals(updateExtRole.getName())) {
260                                         Map<String, String> delRoleKeyMapper = new HashMap<>();
261                                         delRoleKeyMapper.put(ROLE_NAME, name);
262                                         String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);   
263                                         deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
264                                         if (deleteResponse.getStatusCode().value() != 200) {
265                                                 logger.error(EELFLoggerDelegate.errorLogger, "updateRoleInExternalSystem:  Failed to delete role in external system due to {} ", deleteResponse.getBody());
266                                                 throw new Exception(deleteResponse.getBody());
267                                         }
268                                         addRole(updateExtRole, app.getUebKey());
269                                         addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
270                                 }
271                                 ExternalAccessRole updateRole = new ExternalAccessRole();
272                                 if (!isActiveValueChanged
273                                                 || !sysRoleList.getPriority().equals(String.valueOf(updateExtRole.getPriority()))
274                                                 || sysRoleList.getId().equals(IS_NULL_STRING)
275                                                 || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
276                                         String updateDesc = "";
277                                         String appId = (app.getId().equals(PortalConstants.PORTAL_APP_ID)) ? " app_id is null"
278                                                         : APP_ID_EQUALS + app.getId();
279                                         List<EPRole> getRole = dataAccessService.getList(EPRole.class,
280                                                         WHERE_ROLE_NAME_EQUALS + updateExtRole.getName() + "' and " + appId, null, null);
281                                         Map<String, Object> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
282                                         extSystemUpdateRoleJsonMapper.put(ID, getRole.get(0).getId());
283                                         extSystemUpdateRoleJsonMapper.put(ROLE_NAME, updateExtRole.getName());
284                                         extSystemUpdateRoleJsonMapper.put(ACTIVE, updateExtRole.getActive());
285                                         extSystemUpdateRoleJsonMapper.put(PRIORITY, updateExtRole.getPriority());
286                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
287                                                 extSystemUpdateRoleJsonMapper.put(APP_ID, null);
288                                                 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, null);
289                                         } else {
290                                                 extSystemUpdateRoleJsonMapper.put(APP_ID, app.getId());
291                                                 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, getRole.get(0).getAppRoleId());
292
293                                         }
294                                         updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
295                                         updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
296                                         updateRole.setDescription(updateDesc);
297                                         String updateRoleDesc = mapper.writeValueAsString(updateRole);
298                                         HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
299                                         logger.debug(EELFLoggerDelegate.debugLogger,
300                                                         "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
301                                         ResponseEntity<String> updatePermsResponse = template.exchange(
302                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
303                                                         HttpMethod.PUT, entity, String.class);
304                                         logger.debug(EELFLoggerDelegate.debugLogger,
305                                                         "updateRoleInExternalSystem: Finished updating in External Auth system and status code: {} ",
306                                                         updatePermsResponse.getStatusCode().value());
307                                 }
308                                 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
309                                 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
310                                 for (RoleFunction addPerm : roleFunctionListNew) {
311                                         updateRoleFunc.put(addPerm.getCode(), addPerm);
312                                 }
313                                 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
314                                 // Update permissions in the ExternalAccess System
315                                 if (list != null) {
316                                         for (ExternalAccessPerms perm : list) {
317                                                 if (!updateRoleFunc.containsKey(perm.getInstance())) {
318                                                         removePermForRole(perm, mapper, name, headers);
319                                                 }
320                                                 extRolePermMap.put(perm.getInstance(), perm);
321                                         }
322                                 }
323                                 response = true;
324                                 if (!roleFunctionListNew.isEmpty()) {
325                                         for (RoleFunction roleFunc : roleFunctionListNew) {
326                                                 if (!extRolePermMap.containsKey(roleFunc.getCode())) {
327                                                         String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
328                                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(),
329                                                                         "*");
330                                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
331                                                                         app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
332                                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
333                                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
334                                                         logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
335                                                         ResponseEntity<String> addResponse = template.exchange(
336                                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
337                                                                                         + "role/perm",
338                                                                         HttpMethod.POST, entity, String.class);
339                                                         if (addResponse.getStatusCode().value() != 201) {
340                                                                 response = false;
341                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
342                                                                                 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
343                                                                                 addResponse.getStatusCode().getReasonPhrase(),
344                                                                                 addResponse.getStatusCode().value());
345                                                         } else {
346                                                                 response = true;
347                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value());
348                                                         }
349                                                 }
350                                         }
351                                 }
352                         }
353                 } else {
354                         // It seems like role exists in local DB but not in External Access system
355                         addRole(updateExtRole, app.getUebKey());
356                         List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
357                         response = true;
358                         if (!roleFunctionListUpdate.isEmpty()) {
359                                 addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
360                         }
361                 }
362                 return response;
363         }
364         
365         /**
366          * 
367          * It adds functions to the role in external auth system 
368          * 
369          * @param updateExtRole
370          * @param addPermsMapper
371          * @param app
372          * @return true if success else false
373          * @throws Exception
374          */
375         private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app)
376                         throws Exception {
377                 boolean response = false;
378                 ExternalAccessRolePerms extAddRolePerms = null;
379                 ExternalAccessPerms extAddPerms = null;
380                 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
381                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
382                 for (RoleFunction roleFunc : roleFunctionListAdd) {
383                         String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
384                         extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), "*");
385                         extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
386                                         app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
387                         String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
388                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
389                         logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
390                         ResponseEntity<String> addResponse = template.exchange(
391                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
392                                         HttpMethod.POST, entity, String.class);
393                         if (addResponse.getStatusCode().value() != 201) {
394                                 response = false;
395                                 logger.debug(EELFLoggerDelegate.debugLogger,
396                                                 "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
397                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
398                         } else {
399                                 response = true;
400                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value());
401                         }
402                 }
403                 return response;
404         }
405
406         /**
407          * 
408          * It converts list of functions in updateExtRole parameter to the RoleFunction object
409          * 
410          * @param updateExtRole
411          * @return list of functions 
412          */
413         @SuppressWarnings("unchecked")
414         private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
415                 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
416                 List<RoleFunction> roleFunctionList = new ArrayList<>();
417                 ObjectMapper roleFuncMapper = new ObjectMapper();
418                 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
419                 while (itetaror.hasNext()) {
420                         Object nextValue = itetaror.next();
421                         RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
422                         roleFunctionList.add(roleFunction);
423                 }
424                 return roleFunctionList.stream().distinct().collect(Collectors.toList());
425         }
426
427         /**
428          * It delete permissions/functions in the external auth system
429          * 
430          * @param perm
431          * @param permMapper
432          * @param name
433          * @param headers
434          * @throws Exception
435          */
436         private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
437                         throws Exception {
438                 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
439                 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
440                 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
441                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
442                 ResponseEntity<String> deletePermResponse = template
443                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
444                                                 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
445                 if (deletePermResponse.getStatusCode().value() != 200) {
446                         throw new Exception(deletePermResponse.getBody());
447                 }
448                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system and status code: {}",
449                                 deletePermResponse.getStatusCode().value());
450         }
451
452         /**
453          * It will create new role in the External Auth System
454          * 
455          * @param newRole
456          * @param app
457          * @return true if successfully added in the system else false
458          * @throws Exception
459          *             If fails to add role in the system
460          */
461         private boolean addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception {
462                 boolean response = false;
463                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
464                 ObjectMapper mapper = new ObjectMapper();
465                 String addNewRole = "";
466                 ExternalAccessRole extRole = new ExternalAccessRole();
467                 String addDesc = null;
468                 Map<String, Object> extSystemJsonMapper = new LinkedHashMap<>();
469                 extSystemJsonMapper.put(ID, newRole.get(0).getId());
470                 extSystemJsonMapper.put(ROLE_NAME, newRole.get(0).getName());
471                 extSystemJsonMapper.put(ACTIVE, newRole.get(0).getActive());
472                 extSystemJsonMapper.put(PRIORITY, newRole.get(0).getPriority());
473                 extSystemJsonMapper.put(APP_ID, newRole.get(0).getAppId());
474                 extSystemJsonMapper.put(APP_ROLE_ID, newRole.get(0).getAppRoleId());
475                 addDesc = mapper.writeValueAsString(extSystemJsonMapper);
476                 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_"));
477                 extRole.setDescription(addDesc);
478                 addNewRole = mapper.writeValueAsString(extRole);
479                 HttpEntity<String> deleteEntity = new HttpEntity<>(addNewRole, headers);
480                 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
481                 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
482                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
483                                 HttpMethod.POST, deleteEntity, String.class);
484                 if (addNewRoleInExternalSystem.getStatusCode().value() != 201) {
485                         throw new Exception(addNewRoleInExternalSystem.getBody());
486                 } else {
487                         logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Finished adding into External Auth system and status code: {}",
488                                         addNewRoleInExternalSystem.getStatusCode().value());
489                         response = true;
490                 }
491                 return response;
492         }
493
494         /**
495          * 
496          * It updates existing role in the External Auth System
497          * 
498          * @param addRole
499          *            It Contains role information
500          * @param app
501          * @return string which is formatted to match with the external auth system
502          * @throws JsonProcessingException
503          */
504         @SuppressWarnings("unchecked")
505         private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
506                 ObjectMapper mapper = new ObjectMapper();
507                 String addNewRole = "";
508                 ExternalAccessRole extRole = new ExternalAccessRole();
509                 List<EPRole> role = null;
510                 String addDesc = null;
511                 Map<String, Object> extSystemUpdateRole = new LinkedHashMap<>();
512                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
513                         role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId(), null, null);
514                 } else {
515                         role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId(), null, null);
516                 }
517                 extSystemUpdateRole.put(ID, role.get(0).getId());
518                 extSystemUpdateRole.put(ROLE_NAME, addRole.getName());
519                 extSystemUpdateRole.put(ACTIVE, role.get(0).getActive());
520                 extSystemUpdateRole.put(PRIORITY, role.get(0).getPriority());
521                 extSystemUpdateRole.put(APP_ID, role.get(0).getAppId());
522                 extSystemUpdateRole.put(APP_ROLE_ID, role.get(0).getAppRoleId());
523                 addDesc = mapper.writeValueAsString(extSystemUpdateRole);
524                 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_"));
525                 extRole.setDescription(addDesc);
526                 addNewRole = mapper.writeValueAsString(extRole);
527                 return addNewRole;
528         }
529
530         /**
531          * It create a role in the external auth system and then in our local 
532          * 
533          * @param addRoleInDB
534          * @param app
535          * @return true else false
536          * @throws Exception
537          */
538         @SuppressWarnings("unchecked")
539         @Transactional
540         private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
541                 boolean result = false;
542                 List<EPRole> applicationRoles = null;
543                 EPRole epRole = null;
544                 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
545                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
546                 ObjectMapper mapper = new ObjectMapper();
547                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
548                 while (itetaror.hasNext()) {
549                         Object nextValue = itetaror.next();
550                         RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
551                         roleFunctionListNew.add(roleFunction);
552                 }
553                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
554                 try {
555                         if (addRoleInDB.getId() == null) { // check if it is new role
556                                 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
557                                 EPRole epRoleNew = new EPRole();
558                                 epRoleNew.setActive(addRoleInDB.getActive());
559                                 epRoleNew.setName(addRoleInDB.getName());
560                                 epRoleNew.setPriority(addRoleInDB.getPriority());
561                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
562                                         epRoleNew.setAppId(null);
563                                 } else {
564                                         epRoleNew.setAppId(app.getId());
565                                 }
566                                 dataAccessService.saveDomainObject(epRoleNew, null);
567                                 List<EPRole> getRoleCreated = null;
568                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
569                                         List<EPRole> roleCreated = dataAccessService.getList(EPRole.class,
570                                                         WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null,
571                                                         null);
572                                         EPRole epUpdateRole = roleCreated.get(0);
573                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
574                                         dataAccessService.saveDomainObject(epUpdateRole, null);
575                                         getRoleCreated = dataAccessService.getList(EPRole.class,
576                                                         WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null,
577                                                         null);
578                                 } else {
579                                         getRoleCreated = dataAccessService.getList(EPRole.class,
580                                                         WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id is null", null, null);
581                                 }
582                                 // Add role in External Auth system
583                                 result = addNewRoleInExternalSystem(getRoleCreated, app);
584                         } else { // if role already exists then update it
585                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
586                                         applicationRoles = dataAccessService.getList(EPRole.class,
587                                                         " where app_id is null " + " and role_id = " + addRoleInDB.getId(), null, null);
588                                 } else {
589                                         applicationRoles = dataAccessService.getList(EPRole.class,
590                                                         WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null);
591                                 }
592                                 if (applicationRoles.isEmpty()) {
593                                         applicationRoles = dataAccessService.getList(EPRole.class,
594                                                         WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + addRoleInDB.getName() + "'", null,
595                                                         null);
596                                 }
597                                 updateRoleInExternalSystem(addRoleInDB, app);
598                                 deleteRoleFunction(app, applicationRoles);
599                                 if (!applicationRoles.isEmpty()) {
600                                         epRole = applicationRoles.get(0);
601                                         epRole.setName(addRoleInDB.getName());
602                                         epRole.setPriority(addRoleInDB.getPriority());
603                                         epRole.setActive(addRoleInDB.getActive());
604                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
605                                                 epRole.setAppId(null);
606                                                 epRole.setAppRoleId(null);
607                                         } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
608                                                         && applicationRoles.get(0).getAppRoleId() == null) {
609                                                 epRole.setAppRoleId(epRole.getId());
610                                         }
611                                         dataAccessService.saveDomainObject(epRole, null);
612                                 }
613
614                                 saveRoleFunction(listWithoutDuplicates, app, applicationRoles);
615                                 result = true;
616                         }
617                 } catch (Exception e) {
618                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
619                         throw new Exception(e.getMessage());
620                 }
621                 return result;
622         }
623
624         /**
625          * 
626          * It validates whether role exists in external auth system
627          * 
628          * @param checkRole
629          * @param app
630          * @throws Exception
631          *                                      If role exits
632          */
633         private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
634                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
635                 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(" ", "_");
636                 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
637                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
638                 ResponseEntity<String> checkRoleInExternalSystem = template
639                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
640                                                 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
641                 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
642                         logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
643                         throw new Exception("Role already exists in external system");
644                 }
645         }
646
647         /**
648          * It saves list of functions to the role in portal
649          * 
650          * @param roleFunctionListNew
651          * @param app
652          * @param applicationRoles
653          * @throws Exception
654          */
655         private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles)
656                         throws Exception {
657                 for (RoleFunction roleFunc : roleFunctionListNew) {
658                         EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
659                         appRoleFunc.setAppId(app.getId());
660                         appRoleFunc.setRoleId(applicationRoles.get(0).getId());
661                         appRoleFunc.setCode(roleFunc.getCode());
662                         dataAccessService.saveDomainObject(appRoleFunc, null);
663                 }
664         }
665         
666         /**
667          * It deletes all EPAppRoleFunction records in the portal
668          * 
669          * @param app
670          * @param role
671          */
672         @SuppressWarnings("unchecked")
673         private void deleteRoleFunction(EPApp app, List<EPRole> role) {
674                 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.getList(EPAppRoleFunction.class,
675                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + role.get(0).getId(), null, null);
676                 if (!appRoleFunctionList.isEmpty()) {
677                         for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
678                                 dataAccessService.deleteDomainObject(approleFunction, null);
679                         }
680                 }
681         }
682         
683         @Override
684         @SuppressWarnings("unchecked")
685         public List<EPUser> getUser(String loginId){
686                 return (List<EPUser>) dataAccessService.getList(EPUser.class,
687                                 " where org_user_id = '" + loginId + "'", null, null);
688         }
689
690         @Override
691         public String getUserWithRoles(String loginId, String uebkey) throws Exception {
692                 final Map<String, String> params = new HashMap<>();
693                 List<EPUser> userList = null;
694                 CentralUser cenUser = null;
695                 EPApp app = null;
696                 String result = null;
697                 try {
698                         params.put("orgUserIdValue", loginId);
699                         List<EPApp> appList = getApp(uebkey);
700                         if (!appList.isEmpty()) {
701                                 app = appList.get(0);
702                                 userList = getUser(loginId);
703                                 if (!userList.isEmpty()) {
704                                         EPUser user = userList.get(0);
705                                         ObjectMapper mapper = new ObjectMapper();
706                                         Set<EPUserApp> userAppSet = user.getEPUserApps();
707                                         cenUser = createEPUser(user, userAppSet, app);
708                                         result = mapper.writeValueAsString(cenUser);
709                                 } else if (userList.isEmpty()) {
710                                         throw new Exception("User not found");
711                                 }
712                         } else {
713                                 throw new Exception("Application not found");
714                         }
715                 } catch (Exception e) {
716                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
717                         throw new Exception(e.getMessage());
718                 }
719                 return result;
720         }
721
722         @Override
723         public List<CentralRole> getRolesForApp(String uebkey) throws Exception {
724                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
725                 List<CentralRole> roleList = new ArrayList<>();
726                 final Map<String, Long> params = new HashMap<>();
727                 try {
728                         List<EPApp> app = getApp(uebkey);
729                         List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
730                         createCentralRoleObject(app, appRolesList, roleList, params);
731                 } catch (Exception e) {
732                         throw new Exception("getRolesForApp Failed", e);
733                 }
734                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished getRolesForApp");
735                 return roleList;
736         }
737
738         @SuppressWarnings("unchecked")
739         @Override
740         public List<CentralRoleFunction> getRoleFuncList(String uebkey) throws Exception {
741                 EPApp app = getApp(uebkey).get(0);
742                 List<CentralRoleFunction> getRoleFuncList = null;
743                 final Map<String, Long> params = new HashMap<>();
744                 params.put(APP_ID, app.getId());
745                 // Sync all functions from external system into Ecomp portal DB
746                 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Entering into syncRoleFunctionFromExternalAccessSystem");
747                 syncRoleFunctionFromExternalAccessSystem(app);
748                 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Finished syncRoleFunctionFromExternalAccessSystem");
749                 getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
750                 return getRoleFuncList;
751         }
752
753         /**
754          * It returns user detail information which is deep copy of EPUser.class object
755          * 
756          * @param userInfo
757          * @param userAppSet
758          * @param app
759          * @return
760          * @throws Exception
761          */
762         @SuppressWarnings("unchecked")
763         private CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
764
765                 final Map<String, Long> params = new HashMap<>();
766                 CentralUser userAppList = new CentralUser();
767                 CentralUser user1 = null;
768                 try {
769                         userAppList.userApps = new TreeSet<CentralUserApp>();
770                         for (EPUserApp userApp : userAppSet) {
771                                 if (userApp.getRole().getActive()) {
772                                         EPApp epApp = userApp.getApp();
773                                         String globalRole = userApp.getRole().getName().toLowerCase();
774                                         if (((epApp.getId().equals(app.getId()))
775                                                         && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
776                                                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
777                                                                         && (globalRole.toLowerCase().startsWith("global_")))) {
778                                                 CentralUserApp cua = new CentralUserApp();
779                                                 cua.setUserId(null);
780                                                 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
781                                                                 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
782                                                                 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
783                                                                 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
784                                                                 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
785                                                                 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
786                                                                 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
787                                                                 epApp.getUebTopicName());
788                                                 cua.setApp(cenApp);
789                                                 params.put("roleId", userApp.getRole().getId());
790                                                 params.put(APP_ID, userApp.getApp().getId());
791                                                 List<CentralRoleFunction> appRoleFunctionList = dataAccessService
792                                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
793                                                 SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
794                                                 for (CentralRoleFunction roleFunc : appRoleFunctionList) {
795                                                         CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(),
796                                                                         roleFunc.getCode(), roleFunc.getName(), null, null);
797                                                         roleFunctionSet.add(cenRoleFunc);
798                                                 }
799                                                 Long userRoleId = null;
800                                                 if (globalRole.toLowerCase().startsWith("global_")
801                                                                 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
802                                                         userRoleId = userApp.getRole().getId();
803                                                 } else {
804                                                         userRoleId = userApp.getRole().getAppRoleId();
805                                                 }
806                                                 CentralRole cenRole = new CentralRole(userRoleId, userApp.getRole().getCreated(),
807                                                                 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
808                                                                 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
809                                                                 userApp.getRole().getName(), userApp.getRole().getActive(),
810                                                                 userApp.getRole().getPriority(), roleFunctionSet, null, null);
811                                                 cua.setRole(cenRole);
812
813                                                 userAppList.userApps.add(cua);
814                                         }
815                                 }
816                         }
817
818                         user1 = new CentralUser(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
819                                         userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
820                                         userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
821                                         userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
822                                         userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
823                                         userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
824                                         userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
825                                         userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
826                                         userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
827                                         userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
828                                         userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
829                                         userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
830                                         userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
831                                         userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
832                                         userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null);
833                 } catch (Exception e) {
834                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
835                         throw new Exception(e.getMessage());
836                 }
837
838                 return user1;
839         }
840
841         @SuppressWarnings("unchecked")
842         @Override
843         public CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception {
844                 final Map<String, Long> params = new HashMap<>();
845                 List<CentralRole> roleList = new ArrayList<>();
846                 CentralRole cenRole = new CentralRole();
847                 List<EPRole> roleInfo = null;
848                 List<EPApp> app = null;
849                 try {
850                         app = getApp(uebkey);
851                         if (app.isEmpty()) {
852                                 throw new Exception("Application not found");
853                         }
854                         String filter = null;
855                         if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
856                                 filter = WHERE_ROLE_ID_EQUALS + roleId + " and app_id is null ";
857                         } else {
858                                 filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId();
859
860                         }
861                         roleInfo = dataAccessService.getList(EPRole.class, filter, null, null);
862                         roleList = createCentralRoleObject(app, roleInfo, roleList, params);
863                         if (roleList.isEmpty()) {
864                                 return cenRole;
865                         }
866
867                 } catch (Exception e) {
868                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
869                         throw new Exception(e.getMessage());
870
871                 }
872                 return roleList.get(0);
873         }
874         
875         /**
876          * 
877          * It returns list of app roles along with role functions and which went through deep copy
878          * 
879          * @param app
880          * @param roleInfo
881          * @param roleList
882          * @param params
883          * @return
884          */
885         @SuppressWarnings("unchecked")
886         private List<CentralRole> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
887                         List<CentralRole> roleList, Map<String, Long> params) {
888                 for (EPRole role : roleInfo) {
889                         params.put("roleId", role.getId());
890                         params.put(APP_ID, app.get(0).getId());
891                         List<CentralRoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
892                                         params, null);
893                         SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
894                         for (CentralRoleFunction roleFunc : cenRoleFuncList) {
895                                 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), roleFunc.getCode(),
896                                                 roleFunc.getName(), null, null);
897                                 roleFunctionSet.add(cenRoleFunc);
898                         }
899                         SortedSet<CentralRole> childRoles = new TreeSet<>();
900                         CentralRole cenRole = null;
901                         if (role.getAppRoleId() == null) {
902                                 cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
903                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
904                                                 roleFunctionSet, childRoles, null);
905                         } else {
906                                 cenRole = new CentralRole(role.getAppRoleId(), role.getCreated(), role.getModified(),
907                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
908                                                 role.getPriority(), roleFunctionSet, childRoles, null);
909                         }
910                         roleList.add(cenRole);
911                 }
912                 return roleList;
913         }
914
915         @SuppressWarnings("unchecked")
916         @Override
917         public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
918                 CentralRoleFunction roleFunc = null;
919                 EPApp app = getApp(uebkey).get(0);
920                 List<CentralRoleFunction> getRoleFuncList = null;
921                 final Map<String, String> params = new HashMap<>();
922                 try {
923                         params.put("functionCode", functionCode);
924                         params.put(APP_ID, String.valueOf(app.getId()));
925                         getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null);
926                         if (getRoleFuncList.isEmpty()) {
927                                 return roleFunc;
928                         }
929
930                 } catch (Exception e) {
931                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
932                         throw new Exception("getRoleFunction failed", e);
933                 }
934                 return getRoleFuncList.get(0);
935         }
936
937         @Override
938         public boolean saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
939                 boolean saveOrUpdateFunction = false;
940                 try {
941                         addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
942                         dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
943                         saveOrUpdateFunction = true;
944                 } catch (Exception e) {
945                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
946                         saveOrUpdateFunction = false;
947                 }
948                 return saveOrUpdateFunction;
949         }
950         
951         /**
952          * It creates application permission in external auth system
953          * 
954          * @param domainCentralRoleFunction
955          * @param app
956          * @throws Exception
957          */
958         @SuppressWarnings("unchecked")
959         private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
960                         throws Exception {
961                 ObjectMapper mapper = new ObjectMapper();
962                 final Map<String, String> params = new HashMap<>();
963                 params.put("functionCd", domainCentralRoleFunction.getCode());
964                 params.put(APP_ID, String.valueOf(app.getId()));
965                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
966                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
967                 List<CentralRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("getAppFunctionDetails", params,
968                                 null);
969                 String roleFuncName = null;
970                 if (!appRoleFunc.isEmpty()) {
971                         roleFuncName = appRoleFunc.get(0).getCode();
972                 } else {
973                         roleFuncName = domainCentralRoleFunction.getCode();
974                 }
975                 String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
976                 HttpEntity<String> getSinglePermEntity = new HttpEntity<>(headers);
977                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} ", CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
978                 ResponseEntity<String> getResponse = template.exchange(
979                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/"
980                                                 + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*",
981                                 HttpMethod.GET, getSinglePermEntity, String.class);
982                 if (getResponse.getStatusCode().value() != 200) {
983                         EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
984                         throw new Exception(getResponse.getBody());
985                 }
986                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished GET permission from External Auth system and response: {} ", getResponse.getBody());
987                 String res = getResponse.getBody();
988                 if (res.equals(IS_EMPTY_JSON_STRING)) {
989                         try {
990                                 extPerms.setAction("*");
991                                 extPerms.setInstance(domainCentralRoleFunction.getCode());
992                                 extPerms.setType(app.getNameSpace() + "." + checkType);
993                                 extPerms.setDescription(domainCentralRoleFunction.getName());
994                                 String updateRole = mapper.writeValueAsString(extPerms);
995                                 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
996                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
997                                 ResponseEntity<String> addPermResponse= template.exchange(
998                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
999                                                 HttpMethod.POST, entity, String.class);
1000                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission in  and status code: {} ", addPermResponse.getStatusCode().value());
1001                         } catch(HttpClientErrorException e){
1002                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1003                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1004                         }catch (Exception e) {
1005                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1006                                                 e);
1007                         }
1008                 } else {
1009                         try {
1010                                 extPerms.setAction("*");
1011                                 extPerms.setInstance(domainCentralRoleFunction.getCode());
1012                                 extPerms.setType(app.getNameSpace() + "." + checkType);
1013                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1014                                 String updateRole = mapper.writeValueAsString(extPerms);
1015                                 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1016                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1017                                 ResponseEntity<String> updatePermResponse = template.exchange(
1018                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1019                                                 HttpMethod.PUT, entity, String.class);
1020                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system and response: {} ", updatePermResponse.getBody());
1021                         } catch(HttpClientErrorException e){
1022                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1023                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1024                         } catch (Exception e) {
1025                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
1026                                                 e);
1027                         }
1028                 }
1029         }
1030
1031         @Override
1032         @Transactional
1033         public boolean deleteCentralRoleFunction(String code, EPApp app) {
1034                 boolean deleteFunctionResponse = false;
1035                 try {
1036                         final Map<String, String> params = new HashMap<>();
1037                         params.put("functionCd", code);
1038                         params.put(APP_ID, String.valueOf(app.getId()));
1039                         CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService
1040                                         .executeNamedQuery("getAppFunctionDetails", params, null).get(0);
1041                         deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1042                         // Delete role function dependency records
1043                         deleteAppRoleFunctions(code, app);
1044                         dataAccessService.deleteDomainObject(domainCentralRoleFunction, null);
1045                         deleteFunctionResponse = true;
1046                 } catch (Exception e) {
1047                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1048                 }
1049                 return deleteFunctionResponse;
1050         }
1051
1052         /**
1053          * It deletes app function record in portal 
1054          * 
1055          * @param code
1056          * @param app
1057          */
1058         private void deleteAppRoleFunctions(String code, EPApp app) {
1059                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1060                                 APP_ID_EQUALS + app.getId() + " and function_cd = '" + code + "'", null);
1061         }
1062         
1063         /**
1064          * 
1065          * It deletes permission in the external auth system  
1066          * 
1067          * @param domainCentralRoleFunction
1068          * @param app
1069          * @throws Exception
1070          */
1071         private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
1072                         throws Exception {
1073                 try {
1074                         ObjectMapper mapper = new ObjectMapper();
1075                         ExternalAccessPerms extPerms = new ExternalAccessPerms();
1076                         String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1077                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1078                         extPerms.setAction("*");
1079                         extPerms.setInstance(domainCentralRoleFunction.getCode());
1080                         extPerms.setType(app.getNameSpace() + "." + checkType);
1081                         extPerms.setDescription(domainCentralRoleFunction.getName());
1082                         String updateRole = mapper.writeValueAsString(extPerms);
1083                         HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1084                         logger.debug(EELFLoggerDelegate.debugLogger,"deleteRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1085                         ResponseEntity<String> delPermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1086                                         + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1087                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system and status code: {} ", delPermResponse.getStatusCode().value());
1088                 } catch(HttpClientErrorException e){
1089                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1090                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1091                 } catch (Exception e) {
1092                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1093                                 logger.debug(EELFLoggerDelegate.debugLogger,
1094                                                 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
1095                                                 e.getMessage());
1096                         } else {
1097                                 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1098                         }
1099                 }
1100         }
1101
1102         @Override
1103         public boolean saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1104                 boolean addRoleResponse = false;
1105                 try {
1106                         EPApp app = getApp(uebkey).get(0);
1107                         addRoleInEcompDB(saveRole, app);
1108                         addRoleResponse = true;
1109                 } catch (Exception e) {
1110                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1111                 }
1112                 return addRoleResponse;
1113         }
1114
1115         @SuppressWarnings("unchecked")
1116         @Override
1117         public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1118                 Session localSession = sessionFactory.openSession();
1119                 Transaction transaction = null;
1120                 boolean result = false;
1121                 try {
1122                         transaction = localSession.beginTransaction();
1123
1124                         List<EPRole> epRoleList = null;
1125                         ResponseEntity<String> deleteResponse = null;
1126                         EPApp app = getApp(uebkey).get(0);
1127                         if (app.getId() == 1) {
1128                                 epRoleList = dataAccessService.getList(EPRole.class,
1129                                                 " where app_id is null " + "and role_name = '" + deleteRole + "'", null, null);
1130                         } else {
1131                                 epRoleList = dataAccessService.getList(EPRole.class,
1132                                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + deleteRole + "'", null, null);
1133                         }
1134                         // Delete app role functions before deleting role
1135                         deleteRoleFunction(app, epRoleList);
1136                         if (app.getId() == 1) {
1137                                 // Delete fn_user_ role
1138                                 dataAccessService.deleteDomainObjects(EPUserApp.class,
1139                                                 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1140
1141                                 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId());
1142                         }
1143                         // Delete Role in External System
1144                         String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "."
1145                                         + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}";
1146                         deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1147                         if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1148                                 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1149                                 logger.error(EELFLoggerDelegate.errorLogger,
1150                                                 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1151                                                 deleteResponse.getBody());
1152                         }
1153                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1154                         transaction.commit();
1155                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1156                         dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1157                         result = true;
1158                 } catch (Exception e) {
1159                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1160                         result = false;
1161                 } finally {
1162                         localSession.close();
1163                 }
1164                 return result;
1165         }
1166
1167         /**
1168          * 
1169          * It deletes application user role in external auth system
1170          * 
1171          * @param role
1172          * @param app
1173          * @param LoginId
1174          * @throws Exception
1175          */
1176         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1177                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1178                 HttpEntity<String> entity = new HttpEntity<>(headers);
1179                 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1180                 ResponseEntity<String> getResponse = template
1181                                 .exchange(
1182                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1183                                                                 + LoginId
1184                                                                 + SystemProperties
1185                                                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1186                                                                 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
1187                                                 HttpMethod.GET, entity, String.class);
1188                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1189                 if (getResponse.getStatusCode().value() != 200) {
1190                         throw new Exception(getResponse.getBody());
1191                 }
1192                 String res = getResponse.getBody();
1193                 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1194                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1195                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1196                         ResponseEntity<String> deleteResponse = template
1197                                         .exchange(
1198                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1199                                                                         + "userRole/" + LoginId
1200                                                                         + SystemProperties
1201                                                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1202                                                                         + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
1203                                                         HttpMethod.DELETE, userRoleentity, String.class);
1204                         if (deleteResponse.getStatusCode().value() != 200) {
1205                                 throw new Exception("Failed to delete user role");
1206                         }
1207                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1208                 }
1209         }
1210
1211         @SuppressWarnings("unchecked")
1212         @Override
1213         public List<CentralRole> getActiveRoles(String uebkey) throws Exception {
1214                 List<CentralRole> roleList = new ArrayList<>();
1215                 try {
1216                         List<EPApp> app = getApp(uebkey);
1217                         final Map<String, Long> params = new HashMap<>();
1218                         // check if portal
1219                         Long appId = null;
1220                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1221                                 appId = app.get(0).getId();
1222                         }
1223                         List<EPRole> epRole = dataAccessService.getList(EPRole.class,
1224                                         WHERE_APP_ID_EQUALS + appId + " and active_yn = 'Y'", null, null);
1225                         roleList = createCentralRoleObject(app, epRole, roleList, params);
1226                 } catch (Exception e) {
1227                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1228                         throw new Exception(e.getMessage());
1229                 }
1230                 return roleList;
1231
1232         }
1233
1234         @SuppressWarnings("unchecked")
1235         @Override
1236         public boolean deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1237                 boolean result = false;
1238                 Session localSession = sessionFactory.openSession();
1239                 Transaction transaction = null;
1240                 EPApp app = null;
1241                 try {
1242                         transaction = localSession.beginTransaction();
1243                         List<EPRole> epRoleList = null;
1244                         app = getApp(uebkey).get(0);
1245                         epRoleList = dataAccessService.getList(EPRole.class,
1246                                         WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + roleId, null, null);
1247                         if (epRoleList.isEmpty()) {
1248                                 epRoleList = dataAccessService.getList(EPRole.class,
1249                                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + roleId, null, null);
1250                         }
1251                         // Delete User Role in External System before deleting role
1252                         deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1253                         // Delete user app roles
1254                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1255                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1256
1257                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId());
1258                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: about to commit the transaction");
1259                         transaction.commit();
1260                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1261                         result = true;
1262                 } catch(HttpClientErrorException e){
1263                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to deleteRoleDependeciesRecord", e);
1264                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1265                 } catch (Exception e) {
1266                         EcompPortalUtils.rollbackTransaction(transaction, "deleteDependencyRoleRecord: rollback, exception = " + e);
1267                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
1268                         result = false;
1269                 } finally {
1270                         localSession.close();
1271                 }
1272                 return result;
1273         }
1274
1275         @Override
1276         @SuppressWarnings("unchecked")
1277         @Transactional
1278         public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1279                 try {
1280                         ResponseEntity<String> response = null;
1281                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1282                         HttpEntity<String> entity = new HttpEntity<>(headers);
1283                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1284                         response = template
1285                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1286                                                         + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1287
1288                         String res = response.getBody();
1289                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ", response.getBody());
1290                         JSONObject jsonObj = new JSONObject(res);
1291                         JSONArray extPerms = jsonObj.getJSONArray("perm");
1292                         for (int i = 0; i < extPerms.length(); i++) {
1293                                 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
1294                                         extPerms.remove(i);
1295                                         i--;
1296                                 }
1297                         }
1298                         ExternalAccessPermsDetail permDetails = null;
1299                         List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
1300                         for (int i = 0; i < extPerms.length(); i++) {
1301                                 if (extPerms.getJSONObject(i).has("roles")) {
1302                                         ObjectMapper rolesListMapper = new ObjectMapper();
1303                                         JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
1304                                         List<String> list = rolesListMapper.readValue(resRoles.toString(),
1305                                                         TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
1306                                         permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1307                                                         extPerms.getJSONObject(i).getString("instance"),
1308                                                         extPerms.getJSONObject(i).getString("action"), list,
1309                                                         extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION));
1310                                         permsDetailList.add(permDetails);
1311                                 } else {
1312                                         permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1313                                                         extPerms.getJSONObject(i).getString("instance"),
1314                                                         extPerms.getJSONObject(i).getString("action"),
1315                                                         extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION));
1316                                         permsDetailList.add(permDetails);
1317                                 }
1318                         }
1319
1320                         final Map<String, Long> params = new HashMap<>();
1321                         final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>();
1322                         params.put(APP_ID, app.getId());
1323                         List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1324                                         null);
1325                         if (!appFunctions.isEmpty()) {
1326                                 for (CentralRoleFunction roleFunc : appFunctions) {
1327                                         roleFuncMap.put(roleFunc.getCode(), roleFunc);
1328                                 }
1329                         }
1330                         // delete all application role functions
1331                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
1332
1333                         // Add if new functions and app role functions were added in external auth system
1334                         for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1335                                 if (!roleFuncMap.containsKey(permsDetail.getInstance())) {
1336                                         try{
1337                                         CentralRoleFunction addFunction = new CentralRoleFunction();
1338                                         addFunction.setAppId(app.getId());
1339                                         addFunction.setCode(permsDetail.getInstance());
1340                                         addFunction.setName(permsDetail.getDescription());
1341                                         dataAccessService.saveDomainObject(addFunction, null);
1342                                         } catch(Exception e){
1343                                                 logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed to add function", e);
1344                                         }
1345                                 }
1346                                 List<EPRole> epRolesList = null;
1347                                 List<String> roles = permsDetail.getRoles();
1348                                 if (roles != null) {
1349                                         for (String roleList : roles) {
1350                                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1351                                                         epRolesList = dataAccessService.getList(EPRole.class,
1352                                                                         " where app_id is null " + " and role_name = '"
1353                                                                                         + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ")
1354                                                                                         + "'",
1355                                                                         null, null);
1356                                                 } else {
1357                                                         epRolesList = dataAccessService.getList(EPRole.class,
1358                                                                         WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1359                                                                                         + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ")
1360                                                                                         + "'",
1361                                                                         null, null);
1362                                                 }
1363                                                 if (epRolesList.isEmpty()) {
1364                                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1365                                                                 epRolesList = dataAccessService.getList(EPRole.class,
1366                                                                                 " where app_id is null " + " and role_name = '"
1367                                                                                                 + roleList.substring(app.getNameSpace().length() + 1) + "'",
1368                                                                                 null, null);
1369                                                         } else {
1370                                                                 epRolesList = dataAccessService.getList(EPRole.class,
1371                                                                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1372                                                                                                 + roleList.substring(app.getNameSpace().length() + 1) + "'",
1373                                                                                 null, null);
1374                                                         }
1375                                                 }
1376                                                 // save all application role functions
1377                                                 if (!epRolesList.isEmpty()) {
1378                                                         try{
1379                                                         EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1380                                                         addAppRoleFunc.setAppId(app.getId());
1381                                                         addAppRoleFunc.setCode(permsDetail.getInstance());
1382                                                         addAppRoleFunc.setRoleId(epRolesList.get(0).getId());
1383                                                         dataAccessService.saveDomainObject(addAppRoleFunc, null);
1384                                                         } catch(Exception e){
1385                                                                 logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
1386                                                         }
1387                                                 }
1388                                         }
1389                                 }
1390                         }
1391                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1392                 } catch (Exception e) {
1393                         logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1394
1395                 }
1396         }
1397
1398         @Override
1399         @SuppressWarnings("unchecked")
1400         public Integer bulkUploadFunctions(String uebkey) throws Exception {
1401                 EPApp app = getApp(uebkey).get(0);
1402                 List<RoleFunction> roleFuncList = null;
1403                 roleFuncList = dataAccessService.getList(RoleFunction.class, null);
1404                 CentralRoleFunction cenRoleFunc = null;
1405                 Integer functionsAdded = 0;
1406                 try {
1407                         for (RoleFunction roleFunc : roleFuncList) {
1408                                 cenRoleFunc = new CentralRoleFunction(roleFunc.getCode(), roleFunc.getName());
1409                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1410                                 functionsAdded++;
1411                         }
1412                 } catch(HttpClientErrorException e){
1413                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
1414                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1415                 } catch (Exception e) {
1416                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
1417                 }
1418                 return functionsAdded;
1419         }
1420
1421         @Override
1422         public Integer bulkUploadRoles(String uebkey) throws Exception {
1423                 List<EPApp> app = getApp(uebkey);
1424                 List<EPRole> roles = getAppRoles(app.get(0).getId());
1425                 List<CentralRole> cenRoleList = new ArrayList<>();
1426                 final Map<String, Long> params = new HashMap<>();
1427                 Integer rolesListAdded = 0;
1428                 try {
1429                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
1430                         ObjectMapper mapper = new ObjectMapper();
1431                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
1432                         String roleList = mapper.writeValueAsString(cenRoleList);
1433                         List<Role> roleObjectList = mapper.readValue(roleList,
1434                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
1435                         for (Role role : roleObjectList) {
1436                                 addRoleInExternalSystem(role, app.get(0));
1437                                 rolesListAdded++;
1438                         }
1439                 } catch (Exception e) {
1440                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
1441                         throw new Exception(e.getMessage());
1442                 }
1443                 return rolesListAdded;
1444         }
1445
1446         /**
1447          * It creating new role in external auth system while doing bulk upload
1448          * 
1449          * @param role
1450          * @param app
1451          * @throws Exception
1452          */
1453         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
1454                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
1455                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1456                 try {
1457                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1458                         template.exchange(
1459                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1460                                         HttpMethod.POST, entity, String.class);
1461                 } catch(HttpClientErrorException e){
1462                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
1463                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1464                 } catch (Exception e) {
1465                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1466                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
1467                         } else {
1468                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
1469                         }
1470                 }
1471         }
1472
1473         @Override
1474         @SuppressWarnings("unchecked")
1475         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
1476                 EPApp app = getApp(uebkey).get(0);
1477                 List<EPRole> roles = getAppRoles(app.getId());
1478                 final Map<String, Long> params = new HashMap<>();
1479                 Integer roleFunctions = 0;
1480                 try {
1481                         for (EPRole role : roles) {
1482                                 params.put("roleId", role.getId());
1483                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
1484                                                 params, null);
1485                                 if (!appRoleFunc.isEmpty()) {
1486                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
1487                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
1488                                                 roleFunctions++;
1489                                         }
1490                                 }
1491                         }
1492                 } catch(HttpClientErrorException e){
1493                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
1494                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1495                 } catch (Exception e) {
1496                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
1497                 }
1498                 return roleFunctions;
1499         }
1500         
1501         /**
1502          * Its adding a role function while doing bulk upload
1503          * 
1504          * @param addRoleFunc
1505          * @param role
1506          * @param app
1507          */
1508         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
1509                 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
1510                 ExternalAccessRolePerms extRolePerms = null;
1511                 ExternalAccessPerms extPerms = null;
1512                 ObjectMapper mapper = new ObjectMapper();
1513                 try {
1514                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1515
1516                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
1517                                         addRoleFunc.getFunctionName());
1518                         extRolePerms = new ExternalAccessRolePerms(extPerms,
1519                                         app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1520                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1521                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1522                         template.exchange(
1523                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
1524                                         HttpMethod.POST, entity, String.class);
1525                 } catch (Exception e) {
1526                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1527                                 logger.error(EELFLoggerDelegate.errorLogger,
1528                                                 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
1529                         } else {
1530                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
1531                                                 e.getMessage());
1532                         }
1533                 }
1534         }
1535
1536         @Override
1537         public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
1538                 EPApp app = getApp(uebkey).get(0);
1539                 CentralRoleFunction cenRoleFunc = null;
1540                 for (RoleFunction roleFunction : roleFunctionsList) {
1541                         cenRoleFunc = new CentralRoleFunction(roleFunction.getCode(), roleFunction.getName());
1542                         addRoleFunctionInExternalSystem(cenRoleFunc, app);
1543                 }
1544         }
1545
1546         @Override
1547         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
1548                 EPApp app = getApp(uebkey).get(0);
1549                 for (Role role : roleList) {
1550                         addRoleInExternalSystem(role, app);
1551                 }
1552         }
1553
1554         @SuppressWarnings("unchecked")
1555         @Override
1556         public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
1557                 EPApp app = getApp(uebkey).get(0);
1558                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1559                 for (Role role : roleList) {
1560                         try {
1561                                 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
1562                                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
1563                                 ObjectMapper roleFunctionsMapper = new ObjectMapper();
1564                                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
1565                                 while (itetaror.hasNext()) {
1566                                         Object nextValue = itetaror.next();
1567                                         RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
1568                                         roleFunctionListNew.add(roleFunction);
1569                                 }
1570                                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
1571                                                 .collect(Collectors.toList());
1572                                 for (RoleFunction roleFunction : listWithoutDuplicates) {
1573                                         String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
1574                                         ExternalAccessRolePerms extRolePerms = null;
1575                                         ExternalAccessPerms extPerms = null;
1576                                         ObjectMapper mapper = new ObjectMapper();
1577                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
1578                                                         "*");
1579                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
1580                                                         app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1581                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1582                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1583                                         template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1584                                                         + "role/perm", HttpMethod.PUT, entity, String.class);
1585                                 }
1586                         } catch (Exception e) {
1587                                 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1588                                         logger.error(EELFLoggerDelegate.errorLogger,
1589                                                         "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
1590                                 } else {
1591                                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
1592                                                         e.getMessage());
1593                                 }
1594                         }
1595
1596                 }
1597         }
1598
1599         @Override
1600         @SuppressWarnings("unchecked")
1601         @Transactional
1602         public void syncApplicationRolesWithEcompDB(EPApp app) {
1603                 try {
1604                         ResponseEntity<String> response = null;
1605                         List<EPRole> finalRoleList = new ArrayList<>();
1606                         ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
1607                         ExternalAccessPerms externalAccessPerms = null;
1608                         List<String> functionCodelist = new ArrayList<>();
1609                         List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
1610                         ObjectMapper mapper = new ObjectMapper();
1611                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1612                         HttpEntity<String> entity = new HttpEntity<>(headers);
1613                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1614                         response = template
1615                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1616                                                         + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1617                         String res = response.getBody();
1618                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
1619                                         res);
1620                         JSONObject jsonObj = new JSONObject(res);
1621                         JSONArray extRole = jsonObj.getJSONArray("role");
1622                         for (int i = 0; i < extRole.length(); i++) {
1623                                 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ".admin")
1624                                                 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ".owner")) {
1625                                         extRole.remove(i);
1626                                         i--;
1627                                 }
1628                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get(ROLE_NAME)
1629                                                 .equals(app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))) {
1630                                         extRole.remove(i);
1631                                         i--;
1632                                 }
1633                         }
1634                         List<EPAppRoleFunction> applicationRoleFunctionList = new ArrayList<>();
1635                         for (int i = 0; i < extRole.length(); i++) {
1636                                 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
1637                                 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
1638                                 JSONObject Role = (JSONObject) extRole.get(i);
1639                                 if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
1640                                         ApplicationRole.setActive("true");
1641                                         ApplicationRole.setAppId(IS_NULL_STRING);
1642                                         ApplicationRole.setPriority(IS_NULL_STRING);
1643                                         ApplicationRole.setAppRoleId(IS_NULL_STRING);
1644                                         String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
1645                                         ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
1646                                 } else {
1647                                         String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1648                                         ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
1649                                 }
1650
1651                                 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
1652                                 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
1653                                         JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
1654                                         for (int j = 0; j < extPerm.length(); j++) {
1655                                                 JSONObject perms = extPerm.getJSONObject(j);
1656                                                 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
1657                                                                 perms.getString("instance"), perms.getString("action"));
1658                                                 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
1659                                                 functionCodelist.add(ePAppRoleFunction.getCode());
1660                                                 externalAccessPermsOfRole.add(externalAccessPerms);
1661                                         }
1662                                 }
1663
1664                                 if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
1665                                         externalRoleDetail.setActive(false);
1666                                 } else {
1667                                         externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString()));
1668                                 }
1669                                 externalRoleDetail.setName(ApplicationRole.getName());
1670
1671                                 if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
1672                                         externalRoleDetail.setAppId(null);
1673                                 } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
1674                                         externalRoleDetail.setAppId(app.getId());
1675                                 } else {
1676                                         externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString()));
1677                                 }
1678
1679                                 if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
1680                                         externalRoleDetail.setPriority(null);
1681                                 } else {
1682                                         externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString()));
1683                                 }
1684
1685                                 if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
1686                                         externalRoleDetail.setAppRoleId(null);
1687                                 }
1688
1689                                 if (!externalAccessPermsOfRole.isEmpty()) {
1690                                         for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
1691                                                 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
1692                                                 apRoleFunction.setAppId(app.getId());
1693                                                 apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
1694                                                 apRoleFunction.setCode(externalpermission.getInstance());
1695                                                 applicationRoleFunctionList.add(apRoleFunction);
1696                                         }
1697                                 }
1698                                 externalRoleDetailsList.add(externalRoleDetail);
1699                         }
1700
1701                         for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
1702                                 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
1703                                 finalRoleList.add(ecompRole);
1704                         }
1705
1706                         List<EPRole> applicationRolesList = new ArrayList<>();
1707                         applicationRolesList = getAppRoles(app.getId());
1708                         List<String> applicationRoleIdList = new ArrayList<>();
1709                         for (EPRole applicationRole : applicationRolesList) {
1710                                 applicationRoleIdList.add(applicationRole.getName());
1711                         }
1712
1713                         List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
1714                         for (EPRole aafRole : finalRoleList) {
1715                                 if (!applicationRoleIdList.contains(aafRole.getName())) {
1716                                         roleListToBeAddInEcompDB.add(aafRole);
1717                                 }
1718                         }
1719
1720                         // Check if roles exits in external Access system and make it
1721                         // inactive
1722                         final Map<String, EPRole> checkRolesInactive = new HashMap<>();
1723                         for (EPRole extrole : finalRoleList) {
1724                                 checkRolesInactive.put(extrole.getName(), extrole);
1725                         }
1726                         for (EPRole role : applicationRolesList) {
1727                                 final Map<String, String> extRoleParams = new HashMap<>();
1728                                 List<EPRole> roleList = new ArrayList<>();
1729                                 extRoleParams.put("appRoleName", role.getName());
1730                                 if (!checkRolesInactive.containsKey(role.getName())) {
1731                                         if (app.getId() == 1) {
1732                                                 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null);
1733                                         } else {
1734                                                 extRoleParams.put(APP_ID, app.getId().toString());
1735                                                 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null);
1736                                         }
1737                                         EPRole updateRoleInactive = roleList.get(0);
1738                                         updateRoleInactive.setActive(false);
1739                                         dataAccessService.saveDomainObject(updateRoleInactive, null);
1740                                 }
1741                         }
1742
1743                         for (EPRole roleItem : finalRoleList) {
1744                                 final Map<String, String> roleParams = new HashMap<>();
1745                                 List<EPRole> currentList = new ArrayList<>();
1746                                 roleParams.put("appRoleName", roleItem.getName());
1747                                 if (app.getId() == 1) {
1748                                         currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null);
1749                                 } else {
1750                                         roleParams.put(APP_ID, app.getId().toString());
1751                                         currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null);
1752                                 }
1753
1754                                 if (!currentList.isEmpty()) {
1755                                         Boolean aafRoleActive;
1756                                         Boolean localRoleActive;
1757                                         boolean result;
1758                                         aafRoleActive = Boolean.valueOf(roleItem.getActive());
1759                                         localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
1760                                         result = aafRoleActive.equals(localRoleActive);
1761                                         EPRole updateRole = currentList.get(0);
1762
1763                                         if (!result) {
1764                                                 updateRole.setActive(roleItem.getActive());
1765                                                 dataAccessService.saveDomainObject(updateRole, null);
1766                                         }
1767                                         if (roleItem.getPriority() != null
1768                                                         && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
1769                                                 updateRole.setPriority(roleItem.getPriority());
1770                                                 dataAccessService.saveDomainObject(updateRole, null);
1771                                         }
1772                                 }
1773                         }
1774
1775                         EPRole roleToBeAddedInEcompDB = new EPRole();
1776                         for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
1777                                 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
1778                                 if (app.getId() == 1) {
1779                                         roleToBeAddedInEcompDB.setAppRoleId(null);
1780                                 }
1781                                 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
1782                                 List<EPRole> getRoleCreatedInSync = null;
1783                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1784                                         getRoleCreatedInSync = dataAccessService.getList(EPRole.class,
1785                                                         WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "'", null, null);
1786                                         EPRole epUpdateRole = getRoleCreatedInSync.get(0);
1787                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
1788                                         dataAccessService.saveDomainObject(epUpdateRole, null);
1789                                 }
1790                                 List<EPRole> roleList = new ArrayList<>();
1791                                 final Map<String, String> params = new HashMap<>();
1792
1793                                 params.put("appRoleName", roleToBeAddedInEcompDB.getName());
1794                                 if (app.getId() == 1) {
1795                                         roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null);
1796                                 } else {
1797                                         params.put(APP_ID, app.getId().toString());
1798                                         roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null);
1799                                 }
1800                                 EPRole role = roleList.get(0);
1801                                 Role aaFrole = new Role();
1802                                 aaFrole.setId(role.getId());
1803                                 aaFrole.setActive(role.getActive());
1804                                 aaFrole.setPriority(role.getPriority());
1805                                 aaFrole.setName(role.getName());
1806                                 updateRoleInExternalSystem(aaFrole, app);
1807                         }
1808                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
1809                         for (EPAppRoleFunction rolefun : applicationRoleFunctionList) {
1810                                 dataAccessService.saveDomainObject(rolefun, null);
1811                         }
1812                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
1813                 } catch(HttpClientErrorException e){
1814                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e);
1815                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1816                 } catch (Exception e) {
1817                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
1818                 }
1819         }
1820
1821         /**
1822          * 
1823          * It converts from ExternalRoleDetails.class object to EPRole.class object
1824          * 
1825          * @param externalRoleDetails
1826          * @return EPRole object
1827          */
1828         private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
1829                 EPRole role = new EPRole();
1830                 role.setActive(externalRoleDetails.isActive());
1831                 role.setAppId(externalRoleDetails.getAppId());
1832                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
1833                 role.setName(externalRoleDetails.getName());
1834                 role.setPriority(externalRoleDetails.getPriority());
1835                 return role;
1836         }
1837
1838         @SuppressWarnings("unchecked")
1839         @Override
1840         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
1841                 EPApp app = getApp(uebkey).get(0);
1842                 final Map<String, String> params = new HashMap<>();
1843                 params.put("uebKey", app.getUebKey());
1844                 List<BulkUploadUserRoles> userRolesList = null;
1845                 Integer userRolesAdded = 0;
1846                 if (app.getCentralAuth()) {
1847                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
1848                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
1849                                 addUserRoleInExternalSystem(userRolesUpload);
1850                                 userRolesAdded++;
1851                         }
1852                 }
1853                 return userRolesAdded;
1854         }
1855
1856         /**
1857          * Its adding a user role in external auth system while doing bulk upload 
1858          * 
1859          * @param userRolesUpload
1860          */
1861         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
1862                 try {
1863                         String name = "";
1864                         ObjectMapper mapper = new ObjectMapper();
1865                         if (EPCommonSystemProperties
1866                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1867                                 name = userRolesUpload.getOrgUserId()
1868                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1869                         }
1870                         ExternalAccessUser extUser = new ExternalAccessUser(name,
1871                                         userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_"));
1872                         String userRole = mapper.writeValueAsString(extUser);
1873                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1874                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
1875                         template.exchange(
1876                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1877                                         HttpMethod.POST, entity, String.class);
1878                 } catch(HttpClientErrorException e){
1879                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
1880                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1881                 } catch (Exception e) {
1882                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1883                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
1884                         } else {
1885                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e.getMessage());
1886                         }
1887                 }
1888         }
1889
1890         @Override
1891         public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId) throws Exception {
1892                 try {
1893                         String sql = "";
1894                         Query query = null;
1895                         
1896                         //It should delete only when it portal's roleId
1897                         if(appId.equals(PortalConstants.PORTAL_APP_ID)){
1898                         // Delete from fn_role_function
1899                         sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1900                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1901                         query = localSession.createSQLQuery(sql);
1902                         query.executeUpdate();
1903                         
1904                         // Delete from fn_role_composite
1905                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1906                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1907                         query = localSession.createSQLQuery(sql);
1908                         query.executeUpdate();
1909                         }
1910                         
1911                         // Delete from ep_app_role_function
1912                         sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1913                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1914                         query = localSession.createSQLQuery(sql);
1915                         query.executeUpdate();
1916
1917                         // Delete from ep_role_notification
1918                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1919                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1920                         query = localSession.createSQLQuery(sql);
1921                         query.executeUpdate();
1922                         
1923                         // Delete from fn_user_pseudo_role
1924                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1925                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1926                         query = localSession.createSQLQuery(sql);
1927                         query.executeUpdate();
1928
1929                         // Delete form EP_WIDGET_CATALOG_ROLE
1930                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1931                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1932                         query = localSession.createSQLQuery(sql);
1933                         query.executeUpdate();
1934
1935                         // Delete form EP_WIDGET_CATALOG_ROLE
1936                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1937                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1938                         query = localSession.createSQLQuery(sql);
1939                         query.executeUpdate();
1940
1941                         // Delete form fn_menu_functional_roles
1942                         sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1943                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1944                         query = localSession.createSQLQuery(sql);
1945                         query.executeUpdate();
1946
1947                 } catch (Exception e) {
1948                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1949                         throw new Exception("delete Failed" + e.getMessage());
1950                 }
1951
1952         }
1953         
1954         @SuppressWarnings("unchecked")
1955         @Override
1956         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
1957                 List<String> appMenuFunctionsList = null;
1958                 try {
1959                         EPApp app = getApp(uebkey).get(0);
1960                         final Map<String, Long> appParams = new HashMap<>();
1961                         appParams.put(APP_ID, app.getId());
1962                         appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
1963                 } catch (Exception e) {
1964                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
1965                         return appMenuFunctionsList;
1966                 }
1967                 return appMenuFunctionsList;
1968         }
1969 }