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