1 package org.openecomp.portalapp.portal.service;
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.Iterator;
9 import java.util.SortedSet;
10 import java.util.TreeSet;
11 import java.util.stream.Collectors;
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;
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;
62 @Service("externalAccessRolesService")
63 @EnableAspectJAutoProxy
65 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
67 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
70 private DataAccessService dataAccessService;
73 private SessionFactory sessionFactory;
76 RestTemplate template = new RestTemplate();
78 @SuppressWarnings("unchecked")
79 public List<EPRole> getAppRoles(Long appId, Boolean extRequestValue) throws Exception {
80 List<EPRole> applicationRoles = null;
84 filter = " where app_id is null";
86 filter = " where app_id = " + appId;
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());
93 return applicationRoles;
96 @SuppressWarnings("unchecked")
98 public List<EPApp> getApp(String uebkey) throws Exception {
99 List<EPApp> app = null;
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());
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");
116 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
117 + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"),
118 HttpMethod.GET, entity, String.class)
120 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
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) {
139 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
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");
149 public void updateRole(Role addRole, EPApp app) throws Exception {
150 boolean addResponse = updateRoleInExternalSystem(addRole, app);
152 throw new Exception("Failed to update a role");
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");
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!");
190 addRole(updateExtRole, app.getUebKey());
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));
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;
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!");
215 response = addRole(updateExtRole, app.getUebKey());
216 ObjectMapper addPermsMapper = new ObjectMapper();
217 response = addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app);
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\"}";
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() + "\"}";
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");
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");
247 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
248 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
249 for (RoleFunction addPerm : roleFunctionListNew) {
250 updateRoleFunc.put(addPerm.getCode(), addPerm);
252 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
253 // Update permissions in the ExternalAccess System
254 ObjectMapper permMapper = new ObjectMapper();
256 for (ExternalAccessPerms perm : list) {
257 if (!updateRoleFunc.containsKey(perm.getInstance())) {
258 removePermForRole(perm, permMapper, name, headers);
260 extRolePermMap.put(perm.getInstance(), perm);
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(),
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)
278 HttpMethod.POST, entity, String.class);
279 if (addResponse.getStatusCode().value() != 201) {
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());
285 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
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);
296 if (!roleFunctionListUpdate.isEmpty() || roleFunctionListUpdate.size() > 0) {
297 ObjectMapper addPermsMapper = new ObjectMapper();
298 addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app);
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(),
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)
322 HttpMethod.POST, entity, String.class);
323 if (addResponse.getStatusCode().value() != 201) {
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());
329 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
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);
346 return roleFunctionList.stream().distinct().collect(Collectors.toList());
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");
359 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
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() + "\"}";
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");
383 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
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\"}";
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() + "\"}";
409 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_"));
410 extRole.setDescription(addDesc);
411 addNewRole = mapper.writeValueAsString(extRole);
415 @SuppressWarnings("unchecked")
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);
430 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
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);
441 epRoleNew.setAppId(app.getId());
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() +"' and app_id = "+ app.getId(), 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() +"' and app_id = "+ app.getId() , null, null);
454 getRoleCreated = dataAccessService.getList(EPRole.class,
455 " where role_name = '" + addRoleInDB.getName() +"' and app_id is null", null, null);
457 // Add role in External Access system
458 boolean response = addNewRoleInExternalSystem(getRoleCreated, app);
461 throw new Exception("Failed to add role!");
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);
468 applicationRoles = dataAccessService.getList(EPRole.class,
469 " where app_id = " + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null);
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);
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());
488 dataAccessService.saveDomainObject(epRole, null);
491 saveRoleFunction(listWithoutDuplicates, app, applicationRoles);
494 } catch (Exception e) {
495 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
496 throw new Exception(e.getMessage());
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");
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);
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);
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;
541 String result = null;
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");
559 throw new Exception("Application not found");
561 } catch (Exception e) {
562 logger.error(EELFLoggerDelegate.errorLogger, "getUser is failed", e);
563 throw new Exception(e.getMessage());
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<>();
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);
580 logger.debug(EELFLoggerDelegate.debugLogger, "Finished getRolesForApp");
584 @SuppressWarnings("unchecked")
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;
599 @SuppressWarnings("unchecked")
600 public CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
602 final Map<String, Long> params = new HashMap<>();
603 CentralUser userAppList = new CentralUser();
604 CentralUser user1 = null;
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.toLowerCase().startsWith("global_")))) {
615 CentralUserApp cua = new CentralUserApp();
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());
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);
636 Long userRoleId = null;
637 if(globalRole.toLowerCase().startsWith("global_") && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)){
638 userRoleId = userApp.getRole().getId();
640 userRoleId = userApp.getRole().getAppRoleId();
642 CentralRole cenRole = new CentralRole(userRoleId,
643 userApp.getRole().getCreated(), userApp.getRole().getModified(),
644 userApp.getRole().getCreatedId(), userApp.getRole().getModifiedId(),
645 userApp.getRole().getRowNum(), userApp.getRole().getName(),
646 userApp.getRole().getActive(), userApp.getRole().getPriority(), roleFunctionSet, null,
648 cua.setRole(cenRole);
650 userAppList.userApps.add(cua);
655 user1 = new CentralUser(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
656 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
657 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
658 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
659 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
660 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
661 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
662 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
663 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
664 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
665 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
666 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
667 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
668 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
669 userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null);
670 } catch (Exception e) {
671 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser failed", e);
672 throw new Exception(e.getMessage());
678 @SuppressWarnings("unchecked")
680 public CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception {
681 final Map<String, Long> params = new HashMap<>();
682 List<CentralRole> roleList = new ArrayList<>();
683 CentralRole cenRole = new CentralRole();
684 List<EPRole> roleInfo = null;
685 List<EPApp> app = null;
687 app = getApp(uebkey);
688 if (app.isEmpty() || app.size() == 0) {
689 throw new Exception("Application not found");
691 String filter = null;
692 if (app.get(0).getId() == PortalConstants.PORTAL_APP_ID) {
693 filter = " where role_id = " + roleId + " and app_id is null ";
695 filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId();
698 roleInfo = dataAccessService.getList(EPRole.class, filter, null, null);
699 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
700 if (roleList.isEmpty()) {
704 } catch (Exception e) {
705 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e);
706 throw new Exception(e.getMessage());
709 return roleList.get(0);
712 @SuppressWarnings("unchecked")
713 private List<CentralRole> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
714 List<CentralRole> roleList, Map<String, Long> params) {
715 for (EPRole role : roleInfo) {
716 params.put("roleId", role.getId());
717 params.put("appId", app.get(0).getId());
718 List<CentralRoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
720 SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<CentralRoleFunction>();
721 for (CentralRoleFunction roleFunc : cenRoleFuncList) {
722 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), roleFunc.getCode(),
723 roleFunc.getName(), null, null);
724 roleFunctionSet.add(cenRoleFunc);
726 SortedSet<CentralRole> childRoles = new TreeSet<CentralRole>();
727 CentralRole cenRole = null;
728 if (role.getAppRoleId() == null) {
729 cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
730 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
731 roleFunctionSet, childRoles, null);
733 cenRole = new CentralRole(role.getAppRoleId(), role.getCreated(), role.getModified(),
734 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
735 role.getPriority(), roleFunctionSet, childRoles, null);
737 roleList.add(cenRole);
742 @SuppressWarnings("unchecked")
744 public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
745 CentralRoleFunction roleFunc = null;
746 EPApp app = getApp(uebkey).get(0);
747 List<CentralRoleFunction> getRoleFuncList = null;
748 final Map<String, String> params = new HashMap<>();
750 params.put("functionCode", functionCode);
751 params.put("appId", String.valueOf(app.getId()));
752 getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null);
753 if (getRoleFuncList.isEmpty() | getRoleFuncList.size() == 0) {
757 } catch (Exception e) {
758 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", e);
759 throw new Exception("getRoleFunction failed", e);
761 return getRoleFuncList.get(0);
765 public void saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
767 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
768 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
769 } catch (Exception e) {
770 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction failed", e);
771 throw new Exception(e.getMessage());
775 @SuppressWarnings("unchecked")
776 private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
778 ObjectMapper mapper = new ObjectMapper();
779 final Map<String, String> params = new HashMap<>();
780 params.put("functionCd", domainCentralRoleFunction.getCode());
781 params.put("appId", String.valueOf(app.getId()));
782 ExternalAccessPerms extPerms = new ExternalAccessPerms();
783 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
784 List<CentralRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("getAppFunctionDetails", params,
786 String roleFuncName = null;
787 if (!appRoleFunc.isEmpty()) {
788 roleFuncName = appRoleFunc.get(0).getCode();
790 roleFuncName = domainCentralRoleFunction.getCode();
792 String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
793 HttpEntity<String> getSinglePermEntity = new HttpEntity<>(headers);
794 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
795 ResponseEntity<String> getResponse = template.exchange(
796 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/"
797 + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*",
798 HttpMethod.GET, getSinglePermEntity, String.class);
799 if (getResponse.getStatusCode().value() != 200) {
800 throw new Exception(getResponse.getBody());
802 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
803 String res = getResponse.getBody();
804 if (res.equals("{}")) {
806 extPerms.setAction("*");
807 extPerms.setInstance(domainCentralRoleFunction.getCode());
808 extPerms.setType(app.getNameSpace() + "." + checkType);
809 extPerms.setDescription(domainCentralRoleFunction.getName());
810 String updateRole = mapper.writeValueAsString(extPerms);
811 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
812 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
814 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
815 HttpMethod.POST, entity, String.class);
816 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
818 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add fucntion in external central auth system", e);
822 extPerms.setAction("*");
823 extPerms.setInstance(domainCentralRoleFunction.getCode());
824 extPerms.setType(app.getNameSpace() + "." + checkType);
825 extPerms.setDescription(domainCentralRoleFunction.getName());
826 String updateRole = mapper.writeValueAsString(extPerms);
827 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
828 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
830 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
831 HttpMethod.PUT, entity, String.class);
832 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
833 } catch(Exception e){
834 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add fucntion in external central auth system", e);
842 public void deleteCentralRoleFunction(String code, String uebkey) {
844 EPApp app = getApp(uebkey).get(0);
845 final Map<String, String> params = new HashMap<>();
846 params.put("functionCd", code);
847 params.put("appId", String.valueOf(app.getId()));
848 CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService.executeNamedQuery("getAppFunctionDetails", params, null).get(0);
849 deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
850 //Delete role function dependecy records
851 deleteAppRoleFunctions(code, app);
852 dataAccessService.deleteDomainObject(domainCentralRoleFunction, null);
853 } catch (Exception e) {
854 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction failed", e);
858 private void deleteAppRoleFunctions(String code, EPApp app) {
859 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = "+app.getId()+" and function_cd = '"+ code +"'", null);
862 private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
865 ObjectMapper mapper = new ObjectMapper();
866 ExternalAccessPerms extPerms = new ExternalAccessPerms();
867 String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
868 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
869 extPerms.setAction("*");
870 extPerms.setInstance(domainCentralRoleFunction.getCode());
871 extPerms.setType(app.getNameSpace() + "." + checkType);
872 extPerms.setDescription(domainCentralRoleFunction.getName());
873 String updateRole = mapper.writeValueAsString(extPerms);
874 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
876 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm?force=true",
877 HttpMethod.DELETE, entity, String.class);
878 } catch(Exception e){
879 if(e.getMessage().equalsIgnoreCase("404 Not Found")){
880 logger.debug(EELFLoggerDelegate.debugLogger, " It seems like function is already deleted in external central auth system but exists in local DB", e.getMessage());
882 logger.error(EELFLoggerDelegate.errorLogger, "Failed to delete functions in External System", e);
888 public void saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
890 EPApp app = getApp(uebkey).get(0);
891 addRoleInEcompDB(saveRole, app);
892 } catch (Exception e) {
893 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
894 throw new Exception(e.getMessage());
898 @SuppressWarnings("unchecked")
900 public void deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
901 Session localSession = null;
902 Transaction transaction = null;
903 boolean result = false;
905 localSession = sessionFactory.openSession();
906 transaction = localSession.beginTransaction();
908 List<EPRole> epRoleList = null;
909 ResponseEntity<String> deleteResponse = null;
910 EPApp app = getApp(uebkey).get(0);
913 epRoleList = dataAccessService.getList(EPRole.class,
914 " where app_id is null " + "and role_name = '" + deleteRole +"'", null, null);
917 epRoleList = dataAccessService.getList(EPRole.class,
918 " where app_id = " + app.getId() + " and role_name = '" + deleteRole +"'", null, null);
920 // Delete app role functions before deleting role
921 deleteRoleFunction(app, epRoleList);
924 // Delete fn_user_ role
925 dataAccessService.deleteDomainObjects(EPUserApp.class,
926 " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
928 deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId());
930 // Delete Role in External System
931 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "."
932 + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}";
933 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
934 if (deleteResponse.getStatusCode().value() != 200) {
935 throw new Exception("Failed to delete role in external access system!");
937 logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
938 transaction.commit();
939 logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
940 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
942 } catch (Exception e) {
943 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication failed", e);
944 throw new Exception(e.getMessage());
946 localSession.close();
949 "Exception occurred in deleteRoleForApplication while closing database session for role: '" + deleteRole + "'.");
954 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
955 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
956 HttpEntity<String> entity = new HttpEntity<>(headers);
957 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
958 ResponseEntity<String> getResponse = template
960 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
963 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
964 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
965 HttpMethod.GET, entity, String.class);
966 if (getResponse.getStatusCode().value() != 200) {
967 throw new Exception(getResponse.getBody());
969 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
970 String res = getResponse.getBody();
971 if (!res.equals("{}")) {
972 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
973 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
974 ResponseEntity<String> deleteResponse = template
976 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
977 + "userRole/" + LoginId
979 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
980 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
981 HttpMethod.DELETE, userRoleentity, String.class);
982 if (deleteResponse.getStatusCode().value() != 200) {
983 throw new Exception("Failed to delete user role");
985 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
989 @SuppressWarnings("unchecked")
991 public List<CentralRole> getActiveRoles(String uebkey) throws Exception {
992 List<CentralRole> roleList = new ArrayList<>();
994 List<EPApp> app = getApp(uebkey);
995 final Map<String, Long> params = new HashMap<>();
998 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
999 appId = app.get(0).getId();
1001 List<EPRole> epRole = dataAccessService.getList(EPRole.class,
1002 " where app_id = " + appId + " and active_yn = 'Y'", null, null);
1003 roleList = createCentralRoleObject(app, epRole, roleList, params);
1004 } catch (Exception e) {
1005 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e);
1006 throw new Exception(e.getMessage());
1012 @SuppressWarnings("unchecked")
1014 public void deleteDependcyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1015 boolean result = false;
1016 Session localSession = null;
1017 Transaction transaction = null;
1020 localSession = sessionFactory.openSession();
1021 transaction = localSession.beginTransaction();
1022 List<EPRole> epRoleList = null;
1023 app = getApp(uebkey).get(0);
1024 epRoleList = dataAccessService.getList(EPRole.class,
1025 " where app_id = " + app.getId() + " and app_role_id = " + roleId, null, null);
1026 if(epRoleList.isEmpty()){
1027 epRoleList = dataAccessService.getList(EPRole.class,
1028 " where app_id = " + app.getId() + " and role_id = " + roleId, null, null);
1030 // Delete User Role in External System before deleting role
1031 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1032 // Delete user app roles
1033 dataAccessService.deleteDomainObjects(EPUserApp.class,
1034 " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1036 deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId());
1037 logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
1038 transaction.commit();
1039 logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
1041 } catch (Exception e) {
1042 EcompPortalUtils.rollbackTransaction(transaction,
1043 "deleteDependcyRoleRecord rollback, exception = " + e);
1044 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
1046 localSession.close();
1048 throw new Exception(
1049 "Exception occurred in syncAppRoles while closing database session for role: '" + app.getId() + "'.");
1054 @SuppressWarnings("unchecked")
1056 public void syncRoleFunctionFromExternalAccessSystem(EPApp app){
1058 ResponseEntity<String> response = null;
1059 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1060 HttpEntity<String> entity = new HttpEntity<>(headers);
1061 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1062 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1063 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1065 String res = response.getBody();
1066 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res);
1067 JSONObject jsonObj = new JSONObject(res);
1068 JSONArray extPerms = jsonObj.getJSONArray("perm");
1069 for (int i = 0; i < extPerms.length(); i++) {
1070 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
1075 ExternalAccessPermsDetail permDetails = null;
1076 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
1077 for (int i = 0; i < extPerms.length(); i++) {
1078 if (extPerms.getJSONObject(i).has("roles")) {
1079 ObjectMapper rolesListMapper = new ObjectMapper();
1080 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
1081 List<String> list = rolesListMapper.readValue(resRoles.toString(),
1082 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
1083 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1084 extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"),
1085 list, extPerms.getJSONObject(i).getString("description"));
1086 permsDetailList.add(permDetails);
1088 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1089 extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"),
1090 extPerms.getJSONObject(i).getString("description"));
1091 permsDetailList.add(permDetails);
1095 final Map<String, Long> params = new HashMap<>();
1096 final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>();
1097 params.put("appId", app.getId());
1098 List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1100 if (appFunctions.size() > 0) {
1101 for (CentralRoleFunction roleFunc : appFunctions) {
1102 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1105 // delete all application role functions
1106 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null);
1108 // Add if new functions and app role functions were added in Externalsystem
1109 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1110 if (!roleFuncMap.containsKey(permsDetail.getInstance())) {
1111 CentralRoleFunction addFunction = new CentralRoleFunction();
1112 addFunction.setAppId(app.getId());
1113 addFunction.setCode(permsDetail.getInstance());
1114 addFunction.setName(permsDetail.getDescription());
1115 dataAccessService.saveDomainObject(addFunction, null);
1117 List<EPRole> epRolesList = null;
1118 List<String> roles = permsDetail.getRoles();
1119 if (roles != null) {
1120 for (String roleList : roles) {
1121 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1122 epRolesList = dataAccessService.getList(EPRole.class,
1123 " where app_id is null " + " and role_name = '"
1124 + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'",
1127 epRolesList = dataAccessService.getList(EPRole.class,
1128 " where app_id = " + app.getId() + " and role_name = '"
1129 + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'",
1132 if(epRolesList.isEmpty()){
1133 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1134 epRolesList = dataAccessService.getList(EPRole.class,
1135 " where app_id is null " + " and role_name = '"
1136 + roleList.substring(app.getNameSpace().length() + 1)
1140 epRolesList = dataAccessService.getList(EPRole.class,
1141 " where app_id = " + app.getId() + " and role_name = '"
1142 + roleList.substring(app.getNameSpace().length() + 1)+"'",
1146 // save all application role functions
1147 if (epRolesList.size() > 0 || !epRolesList.isEmpty()) {
1148 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1149 addAppRoleFunc.setAppId(app.getId());
1150 addAppRoleFunc.setCode(permsDetail.getInstance());
1151 addAppRoleFunc.setRoleId(epRolesList.get(0).getId());
1152 dataAccessService.saveDomainObject(addAppRoleFunc, null);
1157 logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem");
1158 } catch(Exception e){
1159 logger.error(EELFLoggerDelegate.errorLogger, "Failed syncRoleFunctionFromExternalAccessSystem", e);
1164 @SuppressWarnings("unchecked")
1165 public Integer bulkUploadFunctions(String uebkey) throws Exception {
1166 EPApp app = getApp(uebkey).get(0);
1167 List<RoleFunction> roleFuncList = null;
1168 roleFuncList = dataAccessService.getList(RoleFunction.class, null);
1169 CentralRoleFunction cenRoleFunc = null;
1170 Integer functionsAdded = 0;
1172 for (RoleFunction roleFunc : roleFuncList) {
1173 cenRoleFunc = new CentralRoleFunction(roleFunc.getCode(), roleFunc.getName());
1174 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1177 } catch (Exception e) {
1178 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e.getMessage(), e);
1180 return functionsAdded;
1183 public Integer bulkUploadRoles(String uebkey) throws Exception {
1184 List<EPApp> app = getApp(uebkey);
1185 List<EPRole> roles = getAppRoles(app.get(0).getId(), null);
1186 List<CentralRole> cenRoleList = new ArrayList<>();
1187 final Map<String, Long> params = new HashMap<>();
1188 Integer rolesListAdded = 0;
1190 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
1191 ObjectMapper mapper = new ObjectMapper();
1192 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
1193 String roleList = mapper.writeValueAsString(cenRoleList);
1194 List<Role> roleObjectList = mapper.readValue(roleList,
1195 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
1196 for (Role role : roleObjectList) {
1197 addRoleInExternalSystem(role, app.get(0));
1200 } catch (Exception e) {
1201 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
1202 throw new Exception(e.getMessage());
1204 return rolesListAdded;
1207 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
1208 String addRoleNew = createNewRoleInExternalSystem(role, app);
1209 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1211 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1213 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1214 HttpMethod.POST, entity, String.class);
1215 } catch(Exception e){
1216 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1217 logger.error(EELFLoggerDelegate.errorLogger, "Role already exits but does not break functionality");
1219 logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleInExternalSystem", e.getMessage());
1224 @SuppressWarnings("unchecked")
1225 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
1226 EPApp app = getApp(uebkey).get(0);
1227 List<EPRole> roles = getAppRoles(app.getId(), null);
1228 final Map<String, Long> params = new HashMap<>();
1229 Integer roleFunctions = 0;
1231 for (EPRole role : roles) {
1232 params.put("roleId", role.getId());
1233 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null);
1234 if(!appRoleFunc.isEmpty()){
1235 for(BulkUploadRoleFunction addRoleFunc : appRoleFunc){
1236 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
1241 } catch (Exception e) {
1242 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions failed", e);
1244 return roleFunctions;
1247 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app){
1248 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
1249 ExternalAccessRolePerms extRolePerms = null;
1250 ExternalAccessPerms extPerms = null;
1251 ObjectMapper mapper = new ObjectMapper();
1253 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1255 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*", addRoleFunc.getFunctionName());
1256 extRolePerms = new ExternalAccessRolePerms(extPerms,
1257 app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1258 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1259 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1261 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1262 + "role/perm", HttpMethod.POST, entity, String.class);
1263 } catch(Exception e){
1264 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1265 logger.error(EELFLoggerDelegate.errorLogger, "RoleFunction already exits but does not break functionality",e);
1267 logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem", e.getMessage());
1273 public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
1274 EPApp app = getApp(uebkey).get(0);
1275 CentralRoleFunction cenRoleFunc = null;
1276 for (RoleFunction roleFunction : roleFunctionsList) {
1277 cenRoleFunc = new CentralRoleFunction(roleFunction.getCode(), roleFunction.getName());
1278 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1283 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
1284 EPApp app = getApp(uebkey).get(0);
1285 for (Role role : roleList) {
1286 addRoleInExternalSystem(role, app);
1290 @SuppressWarnings("unchecked")
1292 public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
1293 EPApp app = getApp(uebkey).get(0);
1294 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1295 for (Role role : roleList) {
1297 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
1298 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
1299 ObjectMapper roleFunctionsMapper = new ObjectMapper();
1300 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
1301 while (itetaror.hasNext()) {
1302 Object nextValue = itetaror.next();
1303 RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
1304 roleFunctionListNew.add(roleFunction);
1306 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
1307 .collect(Collectors.toList());
1308 for (RoleFunction roleFunction : listWithoutDuplicates) {
1309 String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
1310 ExternalAccessRolePerms extRolePerms = null;
1311 ExternalAccessPerms extPerms = null;
1312 ObjectMapper mapper = new ObjectMapper();
1313 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
1315 extRolePerms = new ExternalAccessRolePerms(extPerms,
1316 app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1317 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1318 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1319 template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1320 + "role/perm", HttpMethod.PUT, entity, String.class);
1322 } catch (Exception e) {
1323 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1324 logger.error(EELFLoggerDelegate.errorLogger,
1325 "RoleFunction already exits but does not break functionality");
1327 logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem",
1335 @SuppressWarnings("unchecked")
1337 public void SyncApplicationRolesWithEcompDB(EPApp app){
1339 ResponseEntity<String> response = null;
1340 List<EPRole> finalRoleList = new ArrayList<>();
1341 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
1342 ExternalAccessPerms externalAccessPerms = null;
1343 List<String> functionCodelist = new ArrayList<>();
1344 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
1345 ObjectMapper mapper = new ObjectMapper();
1346 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1347 HttpEntity<String> entity = new HttpEntity<>(headers);
1348 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1349 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1350 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1351 String res = response.getBody();
1352 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res);
1353 JSONObject jsonObj = new JSONObject(res);
1354 JSONArray extRole = jsonObj.getJSONArray("role");
1355 for (int i = 0; i < extRole.length(); i++) {
1356 if (extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1357 || extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")
1362 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get("name").equals(app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))){
1367 List<EPAppRoleFunction> applicationRoleFunctionList = new ArrayList<>();
1368 for (int i = 0; i < extRole.length(); i++) {
1369 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
1370 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
1371 JSONObject Role = (JSONObject) extRole.get(i);
1372 if(!extRole.getJSONObject(i).has("description"))
1374 ApplicationRole.setActive("true");
1375 ApplicationRole.setAppId("null");
1376 ApplicationRole.setPriority("null");
1377 ApplicationRole.setAppRoleId("null");
1378 String roleName =extRole.getJSONObject(i).getString("name");
1379 ApplicationRole.setName(roleName.substring(app.getNameSpace().length()+1));
1382 String desc = extRole.getJSONObject(i).getString("description");
1383 ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
1387 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
1388 if (extRole.getJSONObject(i).has("perms")) {
1389 JSONArray extPerm = (JSONArray) Role.get("perms");
1390 for (int j = 0; j < extPerm.length(); j++) {
1391 JSONObject perms = extPerm.getJSONObject(j);
1392 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), perms.getString("instance"),
1393 perms.getString("action"));
1394 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
1395 functionCodelist.add(ePAppRoleFunction.getCode());
1396 externalAccessPermsOfRole.add(externalAccessPerms);
1400 if (ApplicationRole.getActive().equals("null")) {
1401 externalRoleDetail.setActive(false);
1403 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString()));
1405 externalRoleDetail.setName(ApplicationRole.getName());
1407 if (ApplicationRole.getAppId().equals("null") && app.getId() == 1) {
1408 externalRoleDetail.setAppId(null);
1409 } else if(ApplicationRole.getAppId().equals("null")){
1410 externalRoleDetail.setAppId(app.getId());
1412 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString()));
1415 if (ApplicationRole.getPriority().equals("null")) {
1416 externalRoleDetail.setPriority(null);
1418 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString()));
1421 if (ApplicationRole.getAppRoleId().equals("null") && app.getId() == 1) {
1422 externalRoleDetail.setAppRoleId(null);
1425 if (!externalAccessPermsOfRole.isEmpty() || externalAccessPermsOfRole.size() > 0) {
1426 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
1427 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
1428 apRoleFunction.setAppId(app.getId());
1429 apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
1430 apRoleFunction.setCode(externalpermission.getInstance());
1431 applicationRoleFunctionList.add(apRoleFunction);
1434 externalRoleDetailsList.add(externalRoleDetail);
1437 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
1438 EPRole ecompRole = new EPRole();
1439 ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
1440 finalRoleList.add(ecompRole);
1443 List<EPRole> applicationRolesList = new ArrayList<>();
1444 applicationRolesList = getAppRoles(app.getId(), null);
1445 List<String> applicationRoleIdList = new ArrayList<>();
1446 for (EPRole applicationRole : applicationRolesList) {
1447 applicationRoleIdList.add(applicationRole.getName());
1450 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
1451 for (EPRole aafRole : finalRoleList) {
1452 if (!applicationRoleIdList.contains(aafRole.getName())) {
1453 roleListToBeAddInEcompDB.add(aafRole);
1457 // Check if roles exits in external Access system and make it inactive
1458 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
1459 for(EPRole extrole : finalRoleList){
1460 checkRolesInactive.put(extrole.getName(), extrole);
1462 for (EPRole role : applicationRolesList) {
1463 final Map<String, String> extRoleParams = new HashMap<>();
1464 List<EPRole> roleList = new ArrayList<>();
1465 extRoleParams.put("appRoleName", role.getName());
1466 if (!checkRolesInactive.containsKey(role.getName())) {
1467 if (app.getId() == 1) {
1468 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null);
1470 extRoleParams.put("appId", app.getId().toString());
1471 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null);
1473 EPRole updateRoleInactive = roleList.get(0);
1474 updateRoleInactive.setActive(false);
1475 dataAccessService.saveDomainObject(updateRoleInactive, null);
1479 for (EPRole roleItem : finalRoleList) {
1480 final Map<String, String> roleParams = new HashMap<>();
1481 List<EPRole> currentList = new ArrayList<>();
1482 roleParams.put("appRoleName", roleItem.getName());
1483 if (app.getId() == 1) {
1484 currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null);
1486 roleParams.put("appId", app.getId().toString());
1487 currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null);
1490 if (!currentList.isEmpty()) {
1491 Boolean aafRoleActive;
1492 Boolean localRoleActive;
1494 aafRoleActive = Boolean.valueOf(roleItem.getActive());
1495 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
1496 result = aafRoleActive.equals(localRoleActive);
1497 EPRole updateRole = currentList.get(0);
1500 updateRole.setActive(roleItem.getActive());
1501 dataAccessService.saveDomainObject(updateRole, null);
1503 if (roleItem.getPriority() != null
1504 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
1505 updateRole.setPriority(roleItem.getPriority());
1506 dataAccessService.saveDomainObject(updateRole, null);
1511 EPRole roleToBeAddedInEcompDB = new EPRole();
1512 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
1513 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
1514 if(app.getId() == 1)
1516 roleToBeAddedInEcompDB.setAppRoleId(null);
1518 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
1519 List <EPRole> getRoleCreatedInSync = null;
1520 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1521 getRoleCreatedInSync = dataAccessService.getList(EPRole.class,
1522 " where role_name = '" + roleToBeAddedInEcompDB.getName() +"'", null, null);
1523 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
1524 epUpdateRole.setAppRoleId(epUpdateRole.getId());
1525 dataAccessService.saveDomainObject(epUpdateRole, null);
1527 List<EPRole> roleList = new ArrayList<>();
1528 final Map<String, String> params = new HashMap<>();
1530 params.put("appRoleName", roleToBeAddedInEcompDB.getName());
1531 if (app.getId() == 1) {
1532 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null);
1534 params.put("appId", app.getId().toString());
1535 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null);
1537 EPRole role = roleList.get(0);
1538 Role aaFrole = new Role();
1539 aaFrole.setId(role.getId());
1540 aaFrole.setActive(role.getActive());
1541 aaFrole.setPriority(role.getPriority());
1542 aaFrole.setName(role.getName());
1543 updateRoleInExternalSystem(aaFrole, app);
1545 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null);
1546 for (EPAppRoleFunction rolefun : applicationRoleFunctionList) {
1547 dataAccessService.saveDomainObject(rolefun, null);
1550 logger.debug(EELFLoggerDelegate.debugLogger, "Finished SyncApplicationRolesWithEcompDB");
1551 }catch(Exception e){
1552 logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e);
1556 public EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
1557 EPRole role = new EPRole();
1558 role.setActive(externalRoleDetails.isActive());
1559 role.setAppId(externalRoleDetails.getAppId());
1560 role.setAppRoleId(externalRoleDetails.getAppRoleId());
1561 role.setName(externalRoleDetails.getName());
1562 role.setPriority(externalRoleDetails.getPriority());
1566 @SuppressWarnings("unchecked")
1568 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
1569 EPApp app = getApp(uebkey).get(0);
1570 final Map<String, String> params = new HashMap<>();
1571 params.put("uebKey", app.getUebKey());
1572 List<BulkUploadUserRoles> userRolesList = null;
1573 Integer userRolesAdded = 0;
1574 if (app.getCentralAuth()) {
1575 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
1576 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
1577 addUserRoleInExternalSystem(userRolesUpload);
1581 return userRolesAdded;
1584 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload){
1587 ObjectMapper mapper = new ObjectMapper();
1588 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1589 name = userRolesUpload.getOrgUserId()
1590 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1592 ExternalAccessUser extUser = new ExternalAccessUser(name,
1593 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_"));
1594 String userRole = mapper.writeValueAsString(extUser);
1595 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1596 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
1598 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1599 HttpMethod.POST, entity, String.class);
1600 } catch (Exception e) {
1601 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1602 logger.error(EELFLoggerDelegate.errorLogger, "UserRole already exits but does not break functionality");
1604 logger.error(EELFLoggerDelegate.errorLogger, "Failed to addUserRoleInExternalSystem", e.getMessage());
1610 public void deleteRoleDependeciesRecord(Session localSession, Long roleId) throws Exception {
1612 // Delete from fn_role_function
1613 String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1614 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1615 Query query = localSession.createSQLQuery(sql);
1616 query.executeUpdate();
1618 // Delete from ep_app_role_function
1619 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1620 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1621 query = localSession.createSQLQuery(sql);
1622 query.executeUpdate();
1624 // Delete from ep_role_notification
1625 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1626 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1627 query = localSession.createSQLQuery(sql);
1628 query.executeUpdate();
1630 // Delete from fn_role_composite
1631 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id="
1633 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1634 query = localSession.createSQLQuery(sql);
1635 query.executeUpdate();
1637 // Delete from fn_user_pseudo_role
1638 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1639 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1640 query = localSession.createSQLQuery(sql);
1641 query.executeUpdate();
1643 //Delete form EP_WIDGET_CATALOG_ROLE
1644 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1645 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1646 query = localSession.createSQLQuery(sql);
1647 query.executeUpdate();
1649 //Delete form EP_WIDGET_CATALOG_ROLE
1650 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1651 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1652 query = localSession.createSQLQuery(sql);
1653 query.executeUpdate();
1655 //Delete form fn_menu_functional_roles
1656 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1657 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1658 query = localSession.createSQLQuery(sql);
1659 query.executeUpdate();
1661 } catch (Exception e) {
1662 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord failed " , e);
1663 throw new Exception("delete Failed"+ e.getMessage());
1669 @SuppressWarnings("unchecked")
1671 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
1672 List<String> appMenuFunctionsList = null;
1674 EPApp app = getApp(uebkey).get(0);
1675 final Map<String, Long> appParams = new HashMap<>();
1676 appParams.put("appId", app.getId());
1677 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
1678 } catch(Exception e){
1679 logger.error(EELFLoggerDelegate.errorLogger, "Failed getMenuFunctionsList", e);
1680 return appMenuFunctionsList;
1682 return appMenuFunctionsList;