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.logging.logic.EPLogUtil;
 
  28 import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction;
 
  29 import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles;
 
  30 import org.openecomp.portalapp.portal.transport.CentralApp;
 
  31 import org.openecomp.portalapp.portal.transport.CentralRole;
 
  32 import org.openecomp.portalapp.portal.transport.CentralUser;
 
  33 import org.openecomp.portalapp.portal.transport.CentralUserApp;
 
  34 import org.openecomp.portalapp.portal.transport.ExternalAccessPerms;
 
  35 import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail;
 
  36 import org.openecomp.portalapp.portal.transport.ExternalAccessRole;
 
  37 import org.openecomp.portalapp.portal.transport.ExternalAccessRolePerms;
 
  38 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
 
  39 import org.openecomp.portalapp.portal.transport.ExternalRoleDescription;
 
  40 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
 
  41 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
 
  42 import org.openecomp.portalapp.portal.utils.PortalConstants;
 
  43 import org.openecomp.portalsdk.core.domain.Role;
 
  44 import org.openecomp.portalsdk.core.domain.RoleFunction;
 
  45 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
  46 import org.openecomp.portalsdk.core.service.DataAccessService;
 
  47 import org.openecomp.portalsdk.core.util.SystemProperties;
 
  48 import org.springframework.beans.factory.annotation.Autowired;
 
  49 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
  50 import org.springframework.http.HttpEntity;
 
  51 import org.springframework.http.HttpHeaders;
 
  52 import org.springframework.http.HttpMethod;
 
  53 import org.springframework.http.ResponseEntity;
 
  54 import org.springframework.stereotype.Service;
 
  55 import org.springframework.transaction.annotation.Transactional;
 
  56 import org.springframework.web.client.HttpClientErrorException;
 
  57 import org.springframework.web.client.RestTemplate;
 
  59 import com.fasterxml.jackson.core.JsonProcessingException;
 
  60 import com.fasterxml.jackson.databind.DeserializationFeature;
 
  61 import com.fasterxml.jackson.databind.ObjectMapper;
 
  62 import com.fasterxml.jackson.databind.type.TypeFactory;
 
  64 @Service("externalAccessRolesService")
 
  65 @EnableAspectJAutoProxy
 
  67 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
 
  69         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
 
  72         private DataAccessService dataAccessService;
 
  75         private SessionFactory sessionFactory;
 
  78         RestTemplate template = new RestTemplate();
 
  80         @SuppressWarnings("unchecked")
 
  81         public List<EPRole> getAppRoles(Long appId, Boolean extRequestValue) throws Exception {
 
  82                 List<EPRole> applicationRoles = null;
 
  86                                 filter = " where app_id is null";
 
  88                                 filter = " where app_id = " + appId;
 
  90                         applicationRoles = dataAccessService.getList(EPRole.class, filter, null, null);
 
  91                 } catch (Exception e) {
 
  92                         logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles is failed", e);
 
  93                         throw new Exception(e.getMessage());
 
  95                 return applicationRoles;
 
  98         @SuppressWarnings("unchecked")
 
 100         public List<EPApp> getApp(String uebkey) throws Exception {
 
 101                 List<EPApp> app = null;
 
 103                         app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null);
 
 104                 } catch (Exception e) {
 
 105                         logger.error(EELFLoggerDelegate.errorLogger, "getApp is failed", e);
 
 106                         throw new Exception(e.getMessage());
 
 111         public String getSingleAppRole(String addRole, EPApp app) throws Exception {
 
 112                 String response = "";
 
 113                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 114                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
 115                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 118                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
 
 119                                                                 + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"),
 
 120                                                 HttpMethod.GET, entity, String.class)
 
 122                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 128         public boolean addRole(Role addRole, String uebkey) throws Exception {
 
 129                 boolean response = false;
 
 130                 ResponseEntity<String> addResponse = null;
 
 131                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 132                 EPApp app = getApp(uebkey).get(0);
 
 133                 String newRole = createNewRoleInExternalSystem(addRole, app);
 
 134                 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
 
 135                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 136                 addResponse = template.exchange(
 
 137                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
 138                                 HttpMethod.POST, entity, String.class);
 
 139                 if (addResponse.getStatusCode().value() == 201) {
 
 141                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 143                 if (addResponse.getStatusCode().value() == 406) {
 
 144                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system but something went wrong!");
 
 145                         throw new Exception("Failed to create role");
 
 151         public void updateRole(Role addRole, EPApp app) throws Exception {
 
 152                 boolean addResponse = updateRoleInExternalSystem(addRole, app);
 
 154                         throw new Exception("Failed to update a role");
 
 158         private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
 
 159                 ResponseEntity<String> delResponse = null;
 
 160                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 161                 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
 
 162                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 163                 delResponse = template.exchange(
 
 164                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
 
 165                                 HttpMethod.DELETE, entity, String.class);
 
 166                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 170         @SuppressWarnings("unchecked")
 
 171         private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app) throws Exception {
 
 172                 boolean response = false;
 
 173                 ObjectMapper mapper = new ObjectMapper();
 
 174                 ResponseEntity<String> deleteResponse = null;
 
 175                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 176                 ExternalAccessRolePerms extRolePerms = null;
 
 177                 ExternalAccessPerms extPerms = null;
 
 178                 List<EPRole> epRoleList = null;
 
 179                         epRoleList = dataAccessService.getList(EPRole.class,
 
 180                                 " where role_id = " + updateExtRole.getId(), null, null);
 
 181                 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
 
 182                 if (!appRole.equals("{}")) {
 
 183                         JSONObject jsonObj = new JSONObject(appRole);
 
 184                         JSONArray extRole = jsonObj.getJSONArray("role");
 
 185                         if (!extRole.getJSONObject(0).has("description")) {
 
 186                                 String roleName = extRole.getJSONObject(0).getString("name");
 
 187                                 String delRoleKey = "{\"name\":\"" + roleName + "\"}";
 
 188                                 deleteResponse = deleteRoleInExternalSystem(delRoleKey);
 
 189                                 if (deleteResponse.getStatusCode().value() != 200) {
 
 190                                         throw new Exception("Failed to delete role in external access system!");
 
 192                                 addRole(updateExtRole, app.getUebKey());
 
 194                                 String desc = extRole.getJSONObject(0).getString("description");
 
 195                                 String name = extRole.getJSONObject(0).getString("name");
 
 196                                 List<ExternalAccessPerms> list = null;
 
 197                                 if (extRole.getJSONObject(0).has("perms")) {
 
 198                                         JSONArray perms = extRole.getJSONObject(0).getJSONArray("perms");
 
 199                                         ObjectMapper permsMapper = new ObjectMapper();
 
 200                                         list = permsMapper.readValue(perms.toString(), TypeFactory.defaultInstance()
 
 201                                                         .constructCollectionType(List.class, ExternalAccessPerms.class));
 
 203                                 ObjectMapper roleMapper = new ObjectMapper();
 
 204                                 ExternalRoleDescription sysRoleList = roleMapper.readValue(desc, ExternalRoleDescription.class);
 
 205                                 // If role name or role functions are updated then delete record in External System and add new record to avoid conflicts
 
 206                                 Boolean existingRoleActive;
 
 208                                 // check role active status
 
 209                                 existingRoleActive = new Boolean(sysRoleList.getActive());
 
 210                                 res = existingRoleActive.equals(updateExtRole.getActive());
 
 211                                 if (!sysRoleList.getName().equals(updateExtRole.getName())) {
 
 212                                         String deleteRoleKey = "{\"name\":\"" + name + "\"}";
 
 213                                         deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
 
 214                                         if (deleteResponse.getStatusCode().value() != 200) {
 
 215                                                 throw new Exception("Failed to delete role in external access system!");
 
 217                                         response = addRole(updateExtRole, app.getUebKey());
 
 218                                         ObjectMapper addPermsMapper = new ObjectMapper();
 
 219                                         response = addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app);
 
 221                                 ExternalAccessRole updateRole = new ExternalAccessRole();
 
 222                                 if (!res || !sysRoleList.getPriority().equals(String.valueOf(updateExtRole.getPriority())) || 
 
 223                                                 sysRoleList.getId().equals("null")) {
 
 224                                         String updateDesc = "";
 
 225                                         List<EPRole> getRole = dataAccessService.getList(EPRole.class,
 
 226                                                         " where role_name = '" + updateExtRole.getName() + "'", null, null);
 
 227                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 228                                                 updateDesc = "{\"id\":\"" + getRole.get(0).getId() + "\",\"name\":\"" + updateExtRole.getName()
 
 229                                                                 + "\",\"active\":\"" + updateExtRole.getActive() + "\",\"priority\":\""
 
 230                                                                 + updateExtRole.getPriority() + "\",\"appId\":\"null\",\"appRoleId\":\"null\"}";
 
 233                                                 updateDesc = "{\"id\":\"" + getRole.get(0).getId() + "\",\"name\":\"" + updateExtRole.getName()
 
 234                                                                 + "\",\"active\":\"" + updateExtRole.getActive() + "\",\"priority\":\""
 
 235                                                                 + updateExtRole.getPriority() + "\",\"appId\":\"" + app.getId() + "\",\"appRoleId\":\""
 
 236                                                                 + getRole.get(0).getAppRoleId() + "\"}";
 
 239                                         updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
 
 240                                         updateRole.setDescription(updateDesc);
 
 241                                         String updateRoleDesc = mapper.writeValueAsString(updateRole);
 
 242                                         HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
 
 243                                         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 245                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
 246                                                         HttpMethod.PUT, entity, String.class);
 
 247                                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 249                                 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
 
 250                                 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
 
 251                                 for (RoleFunction addPerm : roleFunctionListNew) {
 
 252                                         updateRoleFunc.put(addPerm.getCode(), addPerm);
 
 254                                 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
 
 255                                 // Update permissions in the ExternalAccess System
 
 256                                 ObjectMapper permMapper = new ObjectMapper();
 
 258                                         for (ExternalAccessPerms perm : list) {
 
 259                                                 if (!updateRoleFunc.containsKey(perm.getInstance())) {
 
 260                                                         removePermForRole(perm, permMapper, name, headers);
 
 262                                                 extRolePermMap.put(perm.getInstance(), perm);
 
 266                                 if (!roleFunctionListNew.isEmpty() || roleFunctionListNew.size() > 0) {
 
 267                                         for (RoleFunction roleFunc : roleFunctionListNew) {
 
 268                                                 if (!extRolePermMap.containsKey(roleFunc.getCode())) {
 
 269                                                         String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
 
 270                                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(),
 
 272                                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
 
 273                                                                         app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
 
 274                                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
 275                                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
 276                                                         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 277                                                         ResponseEntity<String> addResponse = template.exchange(
 
 278                                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 280                                                                         HttpMethod.POST, entity, String.class);
 
 281                                                         if (addResponse.getStatusCode().value() != 201) {
 
 283                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 284                                                                                 "Connected to External Access system but something went wrong! due to {} and statuscode: {}", addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
 
 287                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 294                         // It seems like role exists in local DB but not in External Access  system
 
 295                         addRole(updateExtRole, app.getUebKey());
 
 296                         List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
 
 298                         if (!roleFunctionListUpdate.isEmpty() || roleFunctionListUpdate.size() > 0) {
 
 299                                 ObjectMapper addPermsMapper = new ObjectMapper();
 
 300                                 addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app);
 
 306         private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app) throws Exception {
 
 307                 boolean response = false;
 
 308                 ExternalAccessRolePerms extAddRolePerms = null;
 
 309                 ExternalAccessPerms extAddPerms = null;
 
 310                 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
 
 311                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 312                 for (RoleFunction roleFunc : roleFunctionListAdd) {
 
 313                         String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
 
 314                         extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(),
 
 316                         extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
 
 317                                         app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
 
 318                         String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
 
 319                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
 320                         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 321                         ResponseEntity<String> addResponse = template.exchange(
 
 322                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 324                                         HttpMethod.POST, entity, String.class);
 
 325                         if (addResponse.getStatusCode().value() != 201) {
 
 327                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 328                                                 "Connected to External Access system but something went wrong! due to {} and statuscode: {}", addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
 
 331                                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 337         @SuppressWarnings("unchecked")
 
 338         private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole){
 
 339                 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
 
 340                 List<RoleFunction> roleFunctionList = new ArrayList<>();
 
 341                 ObjectMapper roleFuncMapper = new ObjectMapper();
 
 342                 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
 
 343                 while (itetaror.hasNext()) {
 
 344                         Object nextValue = itetaror.next();
 
 345                         RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
 
 346                         roleFunctionList.add(roleFunction);
 
 348                 return roleFunctionList.stream().distinct().collect(Collectors.toList());
 
 351         private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper,String name, HttpHeaders headers) throws Exception {
 
 352                 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
 
 353                 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
 
 354                 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
 
 355                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 356                 ResponseEntity<String> deletePermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 357                                                 + "role/"+name+"/perm", HttpMethod.DELETE, deleteEntity, String.class);
 
 358                 if (deletePermResponse.getStatusCode().value() != 200) {
 
 359                         throw new Exception("Failed to delete role function");
 
 361                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 364         private boolean addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception {
 
 365                 boolean response = false;
 
 366                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 367                 ObjectMapper mapper = new ObjectMapper();
 
 368                 String addNewRole = "";
 
 369                 ExternalAccessRole extRole = new ExternalAccessRole();
 
 370                 String addDesc = null;
 
 371                 addDesc = "{\"id\":\"" + newRole.get(0).getId() + "\",\"name\":\"" + newRole.get(0).getName() + "\",\"active\":\""
 
 372                                         + newRole.get(0).getActive() + "\",\"priority\":\"" +newRole.get(0).getPriority() + "\",\"appId\":\""
 
 373                                         + newRole.get(0).getAppId() + "\",\"appRoleId\":\"" + newRole.get(0).getAppRoleId() + "\"}";
 
 375                 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_"));
 
 376                 extRole.setDescription(addDesc);
 
 377                 addNewRole = mapper.writeValueAsString(extRole);
 
 378                 HttpEntity<String> deleteEntity = new HttpEntity<>(addNewRole, headers);
 
 379                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 380                 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 381                                                 + "role", HttpMethod.POST, deleteEntity, String.class);
 
 382                 if (addNewRoleInExternalSystem.getStatusCode().value() != 201) {
 
 383                         throw new Exception("Failed to add Role in External System");
 
 385                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 391         @SuppressWarnings("unchecked")
 
 392         private String createNewRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
 
 393                 ObjectMapper mapper = new ObjectMapper();
 
 394                 String addNewRole = "";
 
 395                 ExternalAccessRole extRole = new ExternalAccessRole();
 
 396                 List<EPRole> role = null;
 
 397                 String addDesc = null;
 
 398                 if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 399                         role = dataAccessService.getList(EPRole.class,
 
 400                                         " where role_id = " + addRole.getId(), null, null);     
 
 401                         addDesc = "{\"id\":\"" + role.get(0).getId() + "\",\"name\":\"" + addRole.getName() + "\",\"active\":\""
 
 402                                         + role.get(0).getActive() + "\",\"priority\":\"" + role.get(0).getPriority()
 
 403                                         + "\",\"appId\":\"null\",\"appRoleId\":\"null\"}";
 
 405                         role = dataAccessService.getList(EPRole.class,
 
 406                                         " where app_role_id = " + addRole.getId(), null, null); 
 
 407                         addDesc = "{\"id\":\"" + role.get(0).getId() + "\",\"name\":\"" + addRole.getName() + "\",\"active\":\""
 
 408                                         + role.get(0).getActive() + "\",\"priority\":\"" + addRole.getPriority() + "\",\"appId\":\""
 
 409                                         + app.getId() + "\",\"appRoleId\":\"" + role.get(0).getAppRoleId() + "\"}";
 
 411                 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_"));
 
 412                 extRole.setDescription(addDesc);
 
 413                 addNewRole = mapper.writeValueAsString(extRole);
 
 417         @SuppressWarnings("unchecked")
 
 419         private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
 
 420                 boolean result = false;
 
 421                 List<EPRole> applicationRoles = null;
 
 422                 EPRole epRole = null;
 
 423                 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
 
 424                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
 
 425                 ObjectMapper mapper = new ObjectMapper();
 
 426                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
 
 427                 while (itetaror.hasNext()) {
 
 428                         Object nextValue = itetaror.next();
 
 429                         RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
 
 430                         roleFunctionListNew.add(roleFunction);
 
 432                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
 
 434                         if (addRoleInDB.getId() == null) { // check if it is new role
 
 435                                 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
 
 436                                 EPRole epRoleNew = new EPRole();
 
 437                                 epRoleNew.setActive(addRoleInDB.getActive());
 
 438                                 epRoleNew.setName(addRoleInDB.getName());
 
 439                                 epRoleNew.setPriority(addRoleInDB.getPriority());
 
 440                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 441                                         epRoleNew.setAppId(null);
 
 443                                         epRoleNew.setAppId(app.getId());
 
 445                                 dataAccessService.saveDomainObject(epRoleNew, null);
 
 446                                         List <EPRole> getRoleCreated = null;
 
 447                                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 448                                                 List<EPRole> roleCreated =  dataAccessService.getList(EPRole.class,
 
 449                                                                 " where role_name = '" + addRoleInDB.getName() +"' and app_id = "+ app.getId(), null, null);    
 
 450                                                 EPRole epUpdateRole = roleCreated.get(0);
 
 451                                                 epUpdateRole.setAppRoleId(epUpdateRole.getId());
 
 452                                                 dataAccessService.saveDomainObject(epUpdateRole, null);
 
 453                                                 getRoleCreated =  dataAccessService.getList(EPRole.class,
 
 454                                                                 " where role_name = '" + addRoleInDB.getName() +"' and app_id = "+ app.getId() , null, null);   
 
 456                                                 getRoleCreated =  dataAccessService.getList(EPRole.class,
 
 457                                                                 " where role_name = '" + addRoleInDB.getName() +"' and app_id is null", null, null);    
 
 459                                 // Add role in External Access system
 
 460                                 boolean response = addNewRoleInExternalSystem(getRoleCreated, app);
 
 463                                         throw new Exception("Failed to add role!");
 
 465                         } else { // if role already exists then update it
 
 466                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 467                                         applicationRoles = dataAccessService.getList(EPRole.class,
 
 468                                                         " where app_id is null " + " and role_id = " + addRoleInDB.getId(), null, null);
 
 470                                         applicationRoles = dataAccessService.getList(EPRole.class,
 
 471                                                         " where app_id = " + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null);
 
 473                                 if(applicationRoles.isEmpty() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 474                                         applicationRoles = dataAccessService.getList(EPRole.class,
 
 475                                                         " where app_id = " + app.getId() + " and role_id = " + addRoleInDB.getId(), null, null);
 
 477                                 updateRoleInExternalSystem(addRoleInDB, app);
 
 478                                 deleteRoleFunction(app, applicationRoles);
 
 479                                 if (applicationRoles.size() > 0 || !applicationRoles.isEmpty()) {
 
 480                                         epRole = applicationRoles.get(0);
 
 481                                         epRole.setName(addRoleInDB.getName());
 
 482                                         epRole.setPriority(addRoleInDB.getPriority());
 
 483                                         epRole.setActive(addRoleInDB.getActive());
 
 484                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 485                                                 epRole.setAppId(null);
 
 486                                                 epRole.setAppRoleId(null);
 
 487                                         } else if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && applicationRoles.get(0).getAppRoleId() == null){
 
 488                                                 epRole.setAppRoleId(epRole.getId());
 
 490                                         dataAccessService.saveDomainObject(epRole, null);
 
 493                                 saveRoleFunction(listWithoutDuplicates, app, applicationRoles);
 
 496                 } catch (Exception e) {
 
 497                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
 
 498                         throw new Exception(e.getMessage());
 
 503         private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
 
 504                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 505                 String roleName = app.getNameSpace()+"."+checkRole.getName().replaceAll(" ", "_");
 
 506                 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
 
 507                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 508                 ResponseEntity<String> checkRoleInExternalSystem = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 509                                                 + "roles/"+roleName, HttpMethod.GET, checkRoleEntity, String.class);
 
 510                 if(!checkRoleInExternalSystem.getBody().equals("{}")){
 
 511                         logger.debug("Role already exists in external system ", checkRoleInExternalSystem.getBody());
 
 512                         throw new Exception("Role already exists in external system");
 
 516         private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles) throws Exception {
 
 517                 for (RoleFunction roleFunc : roleFunctionListNew) {
 
 518                         EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
 
 519                         appRoleFunc.setAppId(app.getId());
 
 520                         appRoleFunc.setRoleId(applicationRoles.get(0).getId());
 
 521                         appRoleFunc.setCode(roleFunc.getCode());
 
 522                         dataAccessService.saveDomainObject(appRoleFunc, null);
 
 526         @SuppressWarnings("unchecked")
 
 527         private void deleteRoleFunction(EPApp app, List<EPRole> role) {
 
 528                 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.getList(EPAppRoleFunction.class,
 
 529                                 " where app_id = " + app.getId() + " and role_id = " + role.get(0).getId(), null, null);
 
 530                 if (!appRoleFunctionList.isEmpty() || appRoleFunctionList.size() > 0) {
 
 531                         for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
 
 532                                 dataAccessService.deleteDomainObject(approleFunction, null);
 
 537         @SuppressWarnings("unchecked")
 
 538         public String getUser(String loginId, String uebkey) throws Exception {
 
 539                 final Map<String, String> params = new HashMap<>();
 
 540                 List<EPUser> userList = null;
 
 541                 CentralUser cenUser = null;
 
 543                 String result = null;
 
 545                         params.put("orgUserIdValue", loginId);
 
 546                         List<EPApp> appList = (List<EPApp>) getApp(uebkey);
 
 547                         if (appList.size() > 0) {
 
 548                                 app = appList.get(0);
 
 549                                 userList = (List<EPUser>) dataAccessService.getList(EPUser.class,
 
 550                                                 " where org_user_id = '" + loginId + "'", null, null);
 
 551                                 if (userList.size() > 0) {
 
 552                                         EPUser user = userList.get(0);
 
 553                                         ObjectMapper mapper = new ObjectMapper();
 
 554                                         Set<EPUserApp> userAppSet = user.getEPUserApps();
 
 555                                         cenUser = createEPUser(user, userAppSet, app);
 
 556                                         result = mapper.writeValueAsString(cenUser);
 
 557                                 } else if (userList.size() == 0) {
 
 558                                         throw new Exception("User not found");
 
 561                                 throw new Exception("Application not found");
 
 563                 } catch (Exception e) {
 
 564                         logger.error(EELFLoggerDelegate.errorLogger, "getUser is failed", e);
 
 565                         throw new Exception(e.getMessage());
 
 571         public List<CentralRole> getRolesForApp(String uebkey) throws Exception {
 
 572                 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getRolesForApp");
 
 573                 List<CentralRole> roleList = new ArrayList<>();
 
 574                 final Map<String, Long> params = new HashMap<>();
 
 576                         List<EPApp> app = getApp(uebkey);
 
 577                         List<EPRole> appRolesList = getAppRoles(app.get(0).getId(), null);
 
 578                         createCentralRoleObject(app, appRolesList, roleList, params);
 
 579                 } catch (Exception e) {
 
 580                         throw new Exception("getRolesForApp Failed", e);
 
 582                 logger.debug(EELFLoggerDelegate.debugLogger, "Finished getRolesForApp");
 
 586         @SuppressWarnings("unchecked")
 
 588         public List<CentralRoleFunction> getRoleFuncList(String uebkey) throws Exception {
 
 589                 EPApp app = getApp(uebkey).get(0);
 
 590                 List<CentralRoleFunction> getRoleFuncList = null;
 
 591                 final Map<String, Long> params = new HashMap<>();
 
 592                 params.put("appId", app.getId());
 
 593                 //Sync all functions from external system into Ecomp portal DB
 
 594                 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into syncRoleFunctionFromExternalAccessSystem");
 
 595                 syncRoleFunctionFromExternalAccessSystem(app);
 
 596                 logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem");
 
 597                 getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
 
 598                 return getRoleFuncList;
 
 601         @SuppressWarnings("unchecked")
 
 602         public CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
 
 604                 final Map<String, Long> params = new HashMap<>();
 
 605                 CentralUser userAppList = new CentralUser();
 
 606                 CentralUser user1 = null;
 
 608                         userAppList.userApps = new TreeSet<CentralUserApp>();
 
 609                         for (EPUserApp userApp : userAppSet) {
 
 610                                 if (userApp.getRole().getActive()) {
 
 611                                         EPApp epApp = userApp.getApp();
 
 612                                         String globalRole = userApp.getRole().getName().toLowerCase();
 
 613                                         if (((epApp.getId().equals(app.getId()))
 
 614                                                         && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
 
 615                                                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
 
 616                                                                         && (globalRole.toLowerCase().startsWith("global_")))) {
 
 617                                                 CentralUserApp cua = new CentralUserApp();
 
 619                                                 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
 
 620                                                                 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
 
 621                                                                 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
 
 622                                                                 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
 
 623                                                                 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
 
 624                                                                 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
 
 625                                                                 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
 
 626                                                                 epApp.getUebTopicName());
 
 628                                                 params.put("roleId", userApp.getRole().getId());
 
 629                                                 params.put("appId", userApp.getApp().getId());
 
 630                                                 List<CentralRoleFunction> appRoleFunctionList = dataAccessService
 
 631                                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
 
 632                                                 SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<CentralRoleFunction>();
 
 633                                                 for (CentralRoleFunction roleFunc : appRoleFunctionList) {
 
 634                                                         CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(),
 
 635                                                                         roleFunc.getCode(), roleFunc.getName(), null, null);
 
 636                                                         roleFunctionSet.add(cenRoleFunc);
 
 638                                                 Long userRoleId = null;
 
 639                                                 if(globalRole.toLowerCase().startsWith("global_") && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 640                                                         userRoleId = userApp.getRole().getId();
 
 642                                                         userRoleId = userApp.getRole().getAppRoleId();
 
 644                                                 CentralRole cenRole = new CentralRole(userRoleId,
 
 645                                                                 userApp.getRole().getCreated(), userApp.getRole().getModified(),
 
 646                                                                 userApp.getRole().getCreatedId(), userApp.getRole().getModifiedId(),
 
 647                                                                 userApp.getRole().getRowNum(), userApp.getRole().getName(),
 
 648                                                                 userApp.getRole().getActive(), userApp.getRole().getPriority(), roleFunctionSet, null,
 
 650                                                 cua.setRole(cenRole);
 
 652                                                 userAppList.userApps.add(cua);
 
 657                         user1 = new CentralUser(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
 
 658                                         userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
 
 659                                         userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
 
 660                                         userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
 
 661                                         userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
 
 662                                         userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
 
 663                                         userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
 
 664                                         userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
 
 665                                         userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
 
 666                                         userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
 
 667                                         userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
 
 668                                         userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
 
 669                                         userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
 
 670                                         userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
 
 671                                         userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null);
 
 672                 } catch (Exception e) {
 
 673                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser failed", e);
 
 674                         throw new Exception(e.getMessage());
 
 680         @SuppressWarnings("unchecked")
 
 682         public CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception {
 
 683                 final Map<String, Long> params = new HashMap<>();
 
 684                 List<CentralRole> roleList = new ArrayList<>();
 
 685                 CentralRole cenRole = new CentralRole();
 
 686                 List<EPRole> roleInfo = null;
 
 687                 List<EPApp> app = null;
 
 689                         app = getApp(uebkey);
 
 690                         if (app.isEmpty() || app.size() == 0) {
 
 691                                 throw new Exception("Application not found");
 
 693                         String filter = null;
 
 694                         if (app.get(0).getId() == PortalConstants.PORTAL_APP_ID) {
 
 695                                 filter = " where role_id = " + roleId + " and app_id is null ";
 
 697                                 filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId();
 
 700                         roleInfo = dataAccessService.getList(EPRole.class, filter, null, null);
 
 701                         roleList = createCentralRoleObject(app, roleInfo, roleList, params);
 
 702                         if (roleList.isEmpty()) {
 
 706                 } catch (Exception e) {
 
 707                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e);
 
 708                         throw new Exception(e.getMessage());
 
 711                 return roleList.get(0);
 
 714         @SuppressWarnings("unchecked")
 
 715         private List<CentralRole> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
 
 716                         List<CentralRole> roleList, Map<String, Long> params) {
 
 717                 for (EPRole role : roleInfo) {
 
 718                         params.put("roleId", role.getId());
 
 719                         params.put("appId", app.get(0).getId());
 
 720                         List<CentralRoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
 
 722                         SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<CentralRoleFunction>();
 
 723                         for (CentralRoleFunction roleFunc : cenRoleFuncList) {
 
 724                                 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), roleFunc.getCode(),
 
 725                                                 roleFunc.getName(), null, null);
 
 726                                 roleFunctionSet.add(cenRoleFunc);
 
 728                         SortedSet<CentralRole> childRoles = new TreeSet<CentralRole>();
 
 729                         CentralRole cenRole = null;
 
 730                         if (role.getAppRoleId() == null) {
 
 731                                 cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
 
 732                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
 
 733                                                 roleFunctionSet, childRoles, null);
 
 735                                 cenRole = new CentralRole(role.getAppRoleId(), role.getCreated(), role.getModified(),
 
 736                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
 
 737                                                 role.getPriority(), roleFunctionSet, childRoles, null);
 
 739                         roleList.add(cenRole);
 
 744         @SuppressWarnings("unchecked")
 
 746         public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
 
 747                 CentralRoleFunction roleFunc = null;
 
 748                 EPApp app = getApp(uebkey).get(0);
 
 749                 List<CentralRoleFunction> getRoleFuncList = null;
 
 750                 final Map<String, String> params = new HashMap<>();
 
 752                         params.put("functionCode", functionCode);
 
 753                         params.put("appId", String.valueOf(app.getId()));
 
 754                         getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null);
 
 755                         if (getRoleFuncList.isEmpty() | getRoleFuncList.size() == 0) {
 
 759                 } catch (Exception e) {
 
 760                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", e);
 
 761                         throw new Exception("getRoleFunction failed", e);
 
 763                 return getRoleFuncList.get(0);
 
 767         public void saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
 
 769                         addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
 
 770                         dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
 
 771                 } catch (Exception e) {
 
 772                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction failed", e);
 
 773                         throw new Exception(e.getMessage());
 
 777         @SuppressWarnings("unchecked")
 
 778         private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
 
 780                 ObjectMapper mapper = new ObjectMapper();
 
 781                 final Map<String, String> params = new HashMap<>();
 
 782                 params.put("functionCd", domainCentralRoleFunction.getCode());
 
 783                 params.put("appId", String.valueOf(app.getId()));
 
 784                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
 
 785                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 786                 List<CentralRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("getAppFunctionDetails", params,
 
 788                 String roleFuncName = null;
 
 789                 if (!appRoleFunc.isEmpty()) {
 
 790                         roleFuncName = appRoleFunc.get(0).getCode();
 
 792                         roleFuncName = domainCentralRoleFunction.getCode();
 
 794                 String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
 
 795                 HttpEntity<String> getSinglePermEntity = new HttpEntity<>(headers);
 
 796                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 797                 ResponseEntity<String> getResponse = template.exchange(
 
 798                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/"
 
 799                                                 + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*",
 
 800                                 HttpMethod.GET, getSinglePermEntity, String.class);
 
 801                 if (getResponse.getStatusCode().value() != 200) {
 
 802                         EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
 
 803                         throw new Exception(getResponse.getBody());
 
 805                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 806                 String res = getResponse.getBody();
 
 807                 if (res.equals("{}")) {
 
 809                         extPerms.setAction("*");
 
 810                         extPerms.setInstance(domainCentralRoleFunction.getCode());
 
 811                         extPerms.setType(app.getNameSpace() + "." + checkType);
 
 812                         extPerms.setDescription(domainCentralRoleFunction.getName());
 
 813                         String updateRole = mapper.writeValueAsString(extPerms);
 
 814                         HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
 
 815                         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 817                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
 
 818                                         HttpMethod.POST, entity, String.class);
 
 819                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 820                         }catch(HttpClientErrorException e){
 
 821                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
 
 822                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
 824                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add function in external central auth system", e);
 
 828                         extPerms.setAction("*");
 
 829                         extPerms.setInstance(domainCentralRoleFunction.getCode());
 
 830                         extPerms.setType(app.getNameSpace() + "." + checkType);
 
 831                         extPerms.setDescription(domainCentralRoleFunction.getName());
 
 832                         String updateRole = mapper.writeValueAsString(extPerms);
 
 833                         HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
 
 834                         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 836                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
 
 837                                         HttpMethod.PUT, entity, String.class);
 
 838                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 839                         }catch(HttpClientErrorException e){
 
 840                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
 
 841                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
 843                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add function in external central auth system", e);
 
 851         public void deleteCentralRoleFunction(String code, String uebkey) {
 
 853                         EPApp app = getApp(uebkey).get(0);
 
 854                         final Map<String, String> params = new HashMap<>();
 
 855                         params.put("functionCd", code);
 
 856                         params.put("appId", String.valueOf(app.getId()));
 
 857                         CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService.executeNamedQuery("getAppFunctionDetails", params, null).get(0);
 
 858                         deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
 
 859                         //Delete role function dependecy records
 
 860                         deleteAppRoleFunctions(code, app);
 
 861                         dataAccessService.deleteDomainObject(domainCentralRoleFunction, null);
 
 862                 } catch (Exception e) {
 
 863                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction failed", e);
 
 867         private void deleteAppRoleFunctions(String code, EPApp app) {
 
 868                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = "+app.getId()+" and function_cd = '"+ code +"'", null);
 
 871         private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
 
 874                 ObjectMapper mapper = new ObjectMapper();
 
 875                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
 
 876                 String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
 
 877                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 878                 extPerms.setAction("*");
 
 879                 extPerms.setInstance(domainCentralRoleFunction.getCode());
 
 880                 extPerms.setType(app.getNameSpace() + "." + checkType);
 
 881                 extPerms.setDescription(domainCentralRoleFunction.getName());
 
 882                 String updateRole = mapper.writeValueAsString(extPerms);
 
 883                 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
 
 885                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm?force=true",
 
 886                                 HttpMethod.DELETE, entity, String.class);
 
 887                 } catch(HttpClientErrorException e){
 
 888                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
 
 889                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
 890                 } catch(Exception e){
 
 891                         if(e.getMessage().equalsIgnoreCase("404 Not Found")){
 
 892                         logger.debug(EELFLoggerDelegate.debugLogger, " It seems like function is already deleted in external central auth system  but exists in local DB", e.getMessage());
 
 894                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to delete functions in External System", e);
 
 900         public void saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
 
 902                         EPApp app = getApp(uebkey).get(0);
 
 903                         addRoleInEcompDB(saveRole, app);
 
 904                 } catch (Exception e) {
 
 905                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
 
 906                         throw new Exception(e.getMessage());
 
 910         @SuppressWarnings("unchecked")
 
 912         public void deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
 
 913                 Session localSession = null;
 
 914                 Transaction transaction = null;
 
 915                 boolean result = false;
 
 917                         localSession = sessionFactory.openSession();
 
 918                         transaction = localSession.beginTransaction();
 
 920                         List<EPRole> epRoleList = null;
 
 921                         ResponseEntity<String> deleteResponse = null;
 
 922                         EPApp app = getApp(uebkey).get(0);
 
 925                                 epRoleList = dataAccessService.getList(EPRole.class,
 
 926                                                 " where app_id is null " + "and role_name = '" + deleteRole +"'", null, null);
 
 929                         epRoleList = dataAccessService.getList(EPRole.class,
 
 930                                         " where app_id = " + app.getId() + " and role_name = '" + deleteRole +"'", null, null);
 
 932                         // Delete app role functions before deleting role
 
 933                         deleteRoleFunction(app, epRoleList);
 
 936                                 // Delete fn_user_ role
 
 937                                 dataAccessService.deleteDomainObjects(EPUserApp.class,
 
 938                                                 " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
 
 940                                 deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId());
 
 942                         // Delete Role in External System
 
 943                         String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "."
 
 944                                         + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}";
 
 945                         deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
 
 946                         if (deleteResponse.getStatusCode().value() != 200) {
 
 947                                 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
 
 948                                 throw new Exception("Failed to delete role in external access system!");
 
 950                         logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
 
 951                         transaction.commit();
 
 952                         logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
 
 953                         dataAccessService.deleteDomainObject(epRoleList.get(0), null);
 
 955                 } catch (Exception e) {
 
 956                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication failed", e);
 
 957                         throw new Exception(e.getMessage());
 
 959                         localSession.close();
 
 962                                                 "Exception occurred in deleteRoleForApplication while closing database session for role: '" + deleteRole + "'.");
 
 967         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
 
 968                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 969                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
 970                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 971                 ResponseEntity<String> getResponse = template
 
 973                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
 
 976                                                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
 
 977                                                                 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
 
 978                                                 HttpMethod.GET, entity, String.class);
 
 979                 if (getResponse.getStatusCode().value() != 200) {
 
 980                         throw new Exception(getResponse.getBody());
 
 982                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
 983                 String res = getResponse.getBody();
 
 984                 if (!res.equals("{}")) {
 
 985                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
 
 986                         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
 987                         ResponseEntity<String> deleteResponse = template
 
 989                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 990                                                                         + "userRole/" + LoginId
 
 992                                                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
 
 993                                                                         + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
 
 994                                                         HttpMethod.DELETE, userRoleentity, String.class);
 
 995                         if (deleteResponse.getStatusCode().value() != 200) {
 
 996                                 throw new Exception("Failed to delete user role");
 
 998                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
 
1002         @SuppressWarnings("unchecked")
 
1004         public List<CentralRole> getActiveRoles(String uebkey) throws Exception {
 
1005                 List<CentralRole> roleList = new ArrayList<>();
 
1007                         List<EPApp> app = getApp(uebkey);
 
1008                         final Map<String, Long> params = new HashMap<>();
 
1011                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1012                                 appId = app.get(0).getId();
 
1014                         List<EPRole> epRole = dataAccessService.getList(EPRole.class,
 
1015                                         " where app_id = " + appId + " and active_yn = 'Y'", null, null);
 
1016                         roleList = createCentralRoleObject(app, epRole, roleList, params);
 
1017                 } catch (Exception e) {
 
1018                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e);
 
1019                         throw new Exception(e.getMessage());
 
1025         @SuppressWarnings("unchecked")
 
1027         public void deleteDependcyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
 
1028                 boolean result = false;
 
1029                 Session localSession = null;
 
1030                 Transaction transaction = null;
 
1033                         localSession = sessionFactory.openSession();
 
1034                         transaction = localSession.beginTransaction();
 
1035                         List<EPRole> epRoleList = null;
 
1036                         app = getApp(uebkey).get(0);
 
1037                         epRoleList = dataAccessService.getList(EPRole.class,
 
1038                                         " where app_id = " + app.getId() + " and app_role_id = " + roleId, null, null);
 
1039                         if(epRoleList.isEmpty()){
 
1040                                 epRoleList = dataAccessService.getList(EPRole.class,
 
1041                                                 " where app_id = " + app.getId() + " and role_id = " + roleId, null, null);
 
1043                         // Delete User Role in External System before deleting role
 
1044                         deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
 
1045                         // Delete user app roles
 
1046                         dataAccessService.deleteDomainObjects(EPUserApp.class,
 
1047                                         " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
 
1049                         deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId());
 
1050                         logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
 
1051                         transaction.commit();
 
1052                         logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
 
1054                 }catch(HttpClientErrorException e){
 
1055                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to deleteRoleDependeciesRecord", e);
 
1056                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1057                 }catch (Exception e) {
 
1058                         EcompPortalUtils.rollbackTransaction(transaction,
 
1059                                         "deleteDependcyRoleRecord rollback, exception = " + e);
 
1060                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
 
1062                         localSession.close();
 
1064                                 throw new Exception(
 
1065                                                 "Exception occurred in syncAppRoles while closing database session for role: '" + app.getId() + "'.");
 
1070         @SuppressWarnings("unchecked")
 
1072         public void syncRoleFunctionFromExternalAccessSystem(EPApp app){
 
1074                 ResponseEntity<String> response = null;
 
1075                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1076                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
1077                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
1078                 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1079                                 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
 
1081                 String res = response.getBody();
 
1082                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res);
 
1083                 JSONObject jsonObj = new JSONObject(res);
 
1084                 JSONArray extPerms = jsonObj.getJSONArray("perm");
 
1085                 for (int i = 0; i < extPerms.length(); i++) {
 
1086                         if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
 
1091                 ExternalAccessPermsDetail permDetails = null;
 
1092                 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
 
1093                 for (int i = 0; i < extPerms.length(); i++) {
 
1094                         if (extPerms.getJSONObject(i).has("roles")) {
 
1095                                 ObjectMapper rolesListMapper = new ObjectMapper();
 
1096                                 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
 
1097                                 List<String> list = rolesListMapper.readValue(resRoles.toString(),
 
1098                                                 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
 
1099                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
 
1100                                                 extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"),
 
1101                                                 list, extPerms.getJSONObject(i).getString("description"));
 
1102                                 permsDetailList.add(permDetails);
 
1104                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
 
1105                                                 extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"),
 
1106                                                 extPerms.getJSONObject(i).getString("description"));
 
1107                                 permsDetailList.add(permDetails);
 
1111                 final Map<String, Long> params = new HashMap<>();
 
1112                 final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>();
 
1113                 params.put("appId", app.getId());
 
1114                 List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
 
1116                 if (appFunctions.size() > 0) {
 
1117                         for (CentralRoleFunction roleFunc : appFunctions) {
 
1118                                 roleFuncMap.put(roleFunc.getCode(), roleFunc);
 
1121                 // delete all application role functions
 
1122                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null);
 
1124                 // Add if new functions and app role functions were added in Externalsystem
 
1125                 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
 
1126                         if (!roleFuncMap.containsKey(permsDetail.getInstance())) {
 
1127                                 CentralRoleFunction addFunction = new CentralRoleFunction();
 
1128                                 addFunction.setAppId(app.getId());
 
1129                                 addFunction.setCode(permsDetail.getInstance());
 
1130                                 addFunction.setName(permsDetail.getDescription());
 
1131                                 dataAccessService.saveDomainObject(addFunction, null);
 
1133                                 List<EPRole> epRolesList = null;
 
1134                                 List<String> roles = permsDetail.getRoles();
 
1135                                 if (roles != null) {
 
1136                                 for (String roleList : roles) {
 
1137                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1138                                                 epRolesList = dataAccessService.getList(EPRole.class,
 
1139                                                                 " where app_id is null " + " and role_name = '"
 
1140                                                                                 + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'",
 
1143                                                 epRolesList = dataAccessService.getList(EPRole.class,
 
1144                                                                 " where app_id = " + app.getId() + " and role_name = '"
 
1145                                                                                 + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'",
 
1148                                         if(epRolesList.isEmpty()){
 
1149                                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1150                                                         epRolesList = dataAccessService.getList(EPRole.class,
 
1151                                                                         " where app_id is null " + " and role_name = '"
 
1152                                                                                         + roleList.substring(app.getNameSpace().length() + 1)
 
1156                                                         epRolesList = dataAccessService.getList(EPRole.class,
 
1157                                                                         " where app_id = " + app.getId() + " and role_name = '"
 
1158                                                                                         + roleList.substring(app.getNameSpace().length() + 1)+"'",
 
1162                                         // save all application role functions
 
1163                                         if (epRolesList.size() > 0 || !epRolesList.isEmpty()) {
 
1164                                                 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
 
1165                                                 addAppRoleFunc.setAppId(app.getId());
 
1166                                                 addAppRoleFunc.setCode(permsDetail.getInstance());
 
1167                                                 addAppRoleFunc.setRoleId(epRolesList.get(0).getId());
 
1168                                                 dataAccessService.saveDomainObject(addAppRoleFunc, null);
 
1173                 logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem");
 
1174                 } catch(Exception e){
 
1175                         logger.error(EELFLoggerDelegate.errorLogger, "Failed syncRoleFunctionFromExternalAccessSystem", e);
 
1180         @SuppressWarnings("unchecked")
 
1181         public Integer bulkUploadFunctions(String uebkey) throws Exception {
 
1182                 EPApp app = getApp(uebkey).get(0);
 
1183                 List<RoleFunction> roleFuncList = null;
 
1184                 roleFuncList = dataAccessService.getList(RoleFunction.class, null);
 
1185                 CentralRoleFunction cenRoleFunc = null;
 
1186                 Integer functionsAdded = 0;
 
1188                         for (RoleFunction roleFunc : roleFuncList) {
 
1189                                 cenRoleFunc = new CentralRoleFunction(roleFunc.getCode(), roleFunc.getName());
 
1190                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
 
1193                 }catch(HttpClientErrorException e){
 
1194                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
 
1195                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1196                 }catch (Exception e) {
 
1197                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e.getMessage(), e);
 
1199                 return functionsAdded;
 
1202         public Integer bulkUploadRoles(String uebkey) throws Exception {
 
1203                 List<EPApp> app = getApp(uebkey);
 
1204                 List<EPRole> roles = getAppRoles(app.get(0).getId(), null);
 
1205                 List<CentralRole> cenRoleList = new ArrayList<>();
 
1206                 final Map<String, Long> params = new HashMap<>();
 
1207                 Integer rolesListAdded = 0;
 
1209                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
 
1210                         ObjectMapper mapper = new ObjectMapper();
 
1211                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
 
1212                         String roleList = mapper.writeValueAsString(cenRoleList);
 
1213                         List<Role> roleObjectList = mapper.readValue(roleList,
 
1214                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
 
1215                         for (Role role : roleObjectList) {
 
1216                                 addRoleInExternalSystem(role, app.get(0));
 
1219                 } catch (Exception e) {
 
1220                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
 
1221                         throw new Exception(e.getMessage());
 
1223                 return rolesListAdded;
 
1226         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
 
1227                 String addRoleNew = createNewRoleInExternalSystem(role, app);
 
1228                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1230                 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
 
1232                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
1233                                 HttpMethod.POST, entity, String.class);
 
1234                 }catch(HttpClientErrorException e){
 
1235                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
 
1236                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1237                 }catch(Exception e){
 
1238                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
1239                                 logger.error(EELFLoggerDelegate.errorLogger, "Role already exits but does not break functionality");
 
1241                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleInExternalSystem", e.getMessage());
 
1246         @SuppressWarnings("unchecked")
 
1247         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
 
1248                 EPApp app = getApp(uebkey).get(0);
 
1249                 List<EPRole> roles = getAppRoles(app.getId(), null);
 
1250                 final Map<String, Long> params = new HashMap<>();
 
1251                 Integer roleFunctions = 0;
 
1253                         for (EPRole role : roles) {
 
1254                                 params.put("roleId", role.getId());
 
1255                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null);
 
1256                                 if(!appRoleFunc.isEmpty()){
 
1257                                         for(BulkUploadRoleFunction addRoleFunc : appRoleFunc){
 
1258                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
 
1263                 } catch(HttpClientErrorException e){
 
1264                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
 
1265                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1266                 } catch (Exception e) {
 
1267                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions failed", e);
 
1269                 return roleFunctions;
 
1272         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app){
 
1273                         String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
 
1274                         ExternalAccessRolePerms extRolePerms = null;
 
1275                         ExternalAccessPerms extPerms = null;
 
1276                         ObjectMapper mapper = new ObjectMapper();
 
1278                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1280                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*", addRoleFunc.getFunctionName());
 
1281                         extRolePerms = new ExternalAccessRolePerms(extPerms,
 
1282                                         app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
 
1283                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
1284                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
1286                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1287                                                         + "role/perm", HttpMethod.POST, entity, String.class);
 
1288                         } catch(Exception e){
 
1289                                 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
1290                                         logger.error(EELFLoggerDelegate.errorLogger, "RoleFunction already exits but does not break functionality",e);
 
1292                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem", e.getMessage());
 
1298         public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
 
1299                 EPApp app = getApp(uebkey).get(0);
 
1300                 CentralRoleFunction cenRoleFunc = null;
 
1301                 for (RoleFunction roleFunction : roleFunctionsList) {
 
1302                         cenRoleFunc = new CentralRoleFunction(roleFunction.getCode(), roleFunction.getName());
 
1303                         addRoleFunctionInExternalSystem(cenRoleFunc, app);
 
1308         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
 
1309                 EPApp app = getApp(uebkey).get(0);
 
1310                 for (Role role : roleList) {
 
1311                         addRoleInExternalSystem(role, app);
 
1315         @SuppressWarnings("unchecked")
 
1317         public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
 
1318                 EPApp app = getApp(uebkey).get(0);
 
1319                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1320                 for (Role role : roleList) {
 
1322                                 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
 
1323                                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
 
1324                                 ObjectMapper roleFunctionsMapper = new ObjectMapper();
 
1325                                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
 
1326                                 while (itetaror.hasNext()) {
 
1327                                         Object nextValue = itetaror.next();
 
1328                                         RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
 
1329                                         roleFunctionListNew.add(roleFunction);
 
1331                                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
 
1332                                                 .collect(Collectors.toList());
 
1333                                 for (RoleFunction roleFunction : listWithoutDuplicates) {
 
1334                                         String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
 
1335                                         ExternalAccessRolePerms extRolePerms = null;
 
1336                                         ExternalAccessPerms extPerms = null;
 
1337                                         ObjectMapper mapper = new ObjectMapper();
 
1338                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
 
1340                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
 
1341                                                         app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
 
1342                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
1343                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
1344                                         template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1345                                                         + "role/perm", HttpMethod.PUT, entity, String.class);
 
1347                         } catch (Exception e) {
 
1348                                 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
1349                                         logger.error(EELFLoggerDelegate.errorLogger,
 
1350                                                         "RoleFunction already exits but does not break functionality");
 
1352                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem",
 
1360         @SuppressWarnings("unchecked")
 
1362         public void SyncApplicationRolesWithEcompDB(EPApp app){
 
1364                 ResponseEntity<String> response = null;
 
1365                 List<EPRole> finalRoleList = new ArrayList<>();
 
1366                 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
 
1367                 ExternalAccessPerms externalAccessPerms = null;
 
1368                 List<String> functionCodelist = new ArrayList<>();
 
1369                 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
 
1370                 ObjectMapper mapper = new ObjectMapper();
 
1371                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1372                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
1373                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
1374                 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1375                                 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
 
1376                 String res = response.getBody();
 
1377                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res);
 
1378                 JSONObject jsonObj = new JSONObject(res);
 
1379                 JSONArray extRole = jsonObj.getJSONArray("role");
 
1380                 for (int i = 0; i < extRole.length(); i++) {
 
1381                         if (extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
 
1382                                         || extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")
 
1387                         if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get("name").equals(app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))){
 
1392                 List<EPAppRoleFunction> applicationRoleFunctionList = new ArrayList<>();
 
1393                 for (int i = 0; i < extRole.length(); i++) {
 
1394                         ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
 
1395                         EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
 
1396                         JSONObject Role = (JSONObject) extRole.get(i);
 
1397                         if(!extRole.getJSONObject(i).has("description"))
 
1399                                 ApplicationRole.setActive("true");
 
1400                                         ApplicationRole.setAppId("null");
 
1401                                 ApplicationRole.setPriority("null");
 
1402                                 ApplicationRole.setAppRoleId("null");
 
1403                                 String roleName =extRole.getJSONObject(i).getString("name");
 
1404                                 ApplicationRole.setName(roleName.substring(app.getNameSpace().length()+1));
 
1407                         String desc = extRole.getJSONObject(i).getString("description");
 
1408                         ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
 
1412                         SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
 
1413                         if (extRole.getJSONObject(i).has("perms")) {
 
1414                                 JSONArray extPerm = (JSONArray) Role.get("perms");
 
1415                                 for (int j = 0; j < extPerm.length(); j++) {
 
1416                                         JSONObject perms = extPerm.getJSONObject(j);
 
1417                                         externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), perms.getString("instance"),
 
1418                                                         perms.getString("action"));
 
1419                                         ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
 
1420                                         functionCodelist.add(ePAppRoleFunction.getCode());
 
1421                                         externalAccessPermsOfRole.add(externalAccessPerms);
 
1425                         if (ApplicationRole.getActive().equals("null")) {
 
1426                                 externalRoleDetail.setActive(false);
 
1428                                 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString()));
 
1430                         externalRoleDetail.setName(ApplicationRole.getName());
 
1432                         if (ApplicationRole.getAppId().equals("null") && app.getId() == 1) {
 
1433                                 externalRoleDetail.setAppId(null);
 
1434                         } else if(ApplicationRole.getAppId().equals("null")){
 
1435                                 externalRoleDetail.setAppId(app.getId());
 
1437                                 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString()));
 
1440                         if (ApplicationRole.getPriority().equals("null")) {
 
1441                                 externalRoleDetail.setPriority(null);
 
1443                                 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString()));
 
1446                         if (ApplicationRole.getAppRoleId().equals("null") && app.getId() == 1) {
 
1447                                 externalRoleDetail.setAppRoleId(null);
 
1450                         if (!externalAccessPermsOfRole.isEmpty() || externalAccessPermsOfRole.size() > 0) {
 
1451                                 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
 
1452                                         EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
 
1453                                         apRoleFunction.setAppId(app.getId());
 
1454                                         apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
 
1455                                         apRoleFunction.setCode(externalpermission.getInstance());
 
1456                                         applicationRoleFunctionList.add(apRoleFunction);
 
1459                         externalRoleDetailsList.add(externalRoleDetail);
 
1462                 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
 
1463                         EPRole ecompRole = new EPRole();
 
1464                         ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
 
1465                         finalRoleList.add(ecompRole);
 
1468                 List<EPRole> applicationRolesList = new ArrayList<>();
 
1469                 applicationRolesList = getAppRoles(app.getId(), null);
 
1470                 List<String> applicationRoleIdList = new ArrayList<>();
 
1471                 for (EPRole applicationRole : applicationRolesList) {
 
1472                         applicationRoleIdList.add(applicationRole.getName());
 
1475                 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
 
1476                 for (EPRole aafRole : finalRoleList) {
 
1477                         if (!applicationRoleIdList.contains(aafRole.getName())) {
 
1478                                 roleListToBeAddInEcompDB.add(aafRole);
 
1482                 // Check if roles exits in external Access system and make it inactive
 
1483                 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
 
1484                 for(EPRole extrole : finalRoleList){
 
1485                         checkRolesInactive.put(extrole.getName(), extrole);
 
1487                         for (EPRole role : applicationRolesList) {
 
1488                                 final Map<String, String> extRoleParams = new HashMap<>();
 
1489                                 List<EPRole> roleList = new ArrayList<>();
 
1490                                 extRoleParams.put("appRoleName", role.getName());
 
1491                                 if (!checkRolesInactive.containsKey(role.getName())) {
 
1492                                         if (app.getId() == 1) {
 
1493                                                 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null);
 
1495                                                 extRoleParams.put("appId", app.getId().toString());
 
1496                                                 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null);
 
1498                                         EPRole updateRoleInactive = roleList.get(0);
 
1499                                         updateRoleInactive.setActive(false);
 
1500                                         dataAccessService.saveDomainObject(updateRoleInactive, null);                                   
 
1504                         for (EPRole roleItem : finalRoleList) {
 
1505                                 final Map<String, String> roleParams = new HashMap<>();
 
1506                                 List<EPRole> currentList = new ArrayList<>();
 
1507                                 roleParams.put("appRoleName", roleItem.getName());
 
1508                                 if (app.getId() == 1) {
 
1509                                         currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null);
 
1511                                         roleParams.put("appId", app.getId().toString());
 
1512                                         currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null);
 
1515                                 if (!currentList.isEmpty()) {
 
1516                                         Boolean aafRoleActive;
 
1517                                         Boolean localRoleActive;
 
1519                                         aafRoleActive = Boolean.valueOf(roleItem.getActive());
 
1520                                         localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
 
1521                                         result = aafRoleActive.equals(localRoleActive);
 
1522                                         EPRole updateRole = currentList.get(0);
 
1525                                                 updateRole.setActive(roleItem.getActive());
 
1526                                                 dataAccessService.saveDomainObject(updateRole, null);
 
1528                                         if (roleItem.getPriority() != null
 
1529                                                         && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
 
1530                                                 updateRole.setPriority(roleItem.getPriority());
 
1531                                                 dataAccessService.saveDomainObject(updateRole, null);
 
1536                 EPRole roleToBeAddedInEcompDB = new EPRole();
 
1537                 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
 
1538                         roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
 
1539                         if(app.getId() == 1)
 
1541                                 roleToBeAddedInEcompDB.setAppRoleId(null);
 
1543                         dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
 
1544                         List <EPRole> getRoleCreatedInSync = null;
 
1545                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1546                                 getRoleCreatedInSync =  dataAccessService.getList(EPRole.class,
 
1547                                                 " where role_name = '" + roleToBeAddedInEcompDB.getName() +"'", null, null);    
 
1548                                 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
 
1549                                 epUpdateRole.setAppRoleId(epUpdateRole.getId());
 
1550                                 dataAccessService.saveDomainObject(epUpdateRole, null);
 
1552                         List<EPRole> roleList = new ArrayList<>();
 
1553                         final Map<String, String> params = new HashMap<>();
 
1555                         params.put("appRoleName", roleToBeAddedInEcompDB.getName());
 
1556                         if (app.getId() == 1) {
 
1557                                 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null);
 
1559                                 params.put("appId", app.getId().toString());
 
1560                                 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null);
 
1562                         EPRole role = roleList.get(0);
 
1563                         Role aaFrole = new Role();
 
1564                         aaFrole.setId(role.getId());
 
1565                         aaFrole.setActive(role.getActive());
 
1566                         aaFrole.setPriority(role.getPriority());
 
1567                         aaFrole.setName(role.getName());
 
1568                         updateRoleInExternalSystem(aaFrole, app);
 
1570                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null);
 
1571                         for (EPAppRoleFunction rolefun : applicationRoleFunctionList) {
 
1572                                 dataAccessService.saveDomainObject(rolefun, null);
 
1575                 logger.debug(EELFLoggerDelegate.debugLogger, "Finished SyncApplicationRolesWithEcompDB");
 
1576                 }catch(HttpClientErrorException e){
 
1577                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e);
 
1578                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1579                 }catch(Exception e){
 
1580                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e);
 
1584         public EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
 
1585                 EPRole role = new EPRole();
 
1586                 role.setActive(externalRoleDetails.isActive());
 
1587                 role.setAppId(externalRoleDetails.getAppId());
 
1588                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
 
1589                 role.setName(externalRoleDetails.getName());
 
1590                 role.setPriority(externalRoleDetails.getPriority());
 
1594         @SuppressWarnings("unchecked")
 
1596         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
 
1597                 EPApp app = getApp(uebkey).get(0);
 
1598                 final Map<String, String> params = new HashMap<>();
 
1599                 params.put("uebKey", app.getUebKey());
 
1600                 List<BulkUploadUserRoles> userRolesList = null;
 
1601                 Integer userRolesAdded = 0;
 
1602                 if (app.getCentralAuth()) {
 
1603                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
 
1604                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
 
1605                                 addUserRoleInExternalSystem(userRolesUpload);
 
1609                 return userRolesAdded;
 
1612         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload){
 
1615                 ObjectMapper mapper = new ObjectMapper();
 
1616                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
 
1617                         name = userRolesUpload.getOrgUserId()
 
1618                                         + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
 
1620                 ExternalAccessUser extUser = new ExternalAccessUser(name,
 
1621                                 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_"));
 
1622                 String userRole = mapper.writeValueAsString(extUser);
 
1623                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1624                 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
 
1626                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
 
1627                                 HttpMethod.POST, entity, String.class);
 
1628                 }catch(HttpClientErrorException e){
 
1629                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
 
1630                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1631                 }catch (Exception e) {
 
1632                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
1633                                 logger.error(EELFLoggerDelegate.errorLogger, "UserRole already exits but does not break functionality");
 
1635                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to addUserRoleInExternalSystem", e.getMessage());
 
1641         public void deleteRoleDependeciesRecord(Session localSession, Long roleId) throws Exception {
 
1643                         // Delete from fn_role_function
 
1644                         String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
 
1645                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
1646                         Query query = localSession.createSQLQuery(sql);
 
1647                         query.executeUpdate();
 
1649                         // Delete from ep_app_role_function
 
1650                     sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
 
1651                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
1652                          query = localSession.createSQLQuery(sql);
 
1653                         query.executeUpdate();
 
1655                         // Delete from ep_role_notification
 
1656                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
 
1657                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
1658                         query = localSession.createSQLQuery(sql);
 
1659                         query.executeUpdate();
 
1661                         // Delete from fn_role_composite
 
1662                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id="
 
1664                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
1665                         query = localSession.createSQLQuery(sql);
 
1666                         query.executeUpdate();
 
1668                         // Delete from fn_user_pseudo_role
 
1669                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
 
1670                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
1671                         query = localSession.createSQLQuery(sql);
 
1672                         query.executeUpdate();
 
1674                         //Delete form EP_WIDGET_CATALOG_ROLE
 
1675                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
 
1676                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
1677                         query = localSession.createSQLQuery(sql);
 
1678                         query.executeUpdate();
 
1680                         //Delete form EP_WIDGET_CATALOG_ROLE
 
1681                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
 
1682                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
1683                         query = localSession.createSQLQuery(sql);
 
1684                         query.executeUpdate();
 
1686                         //Delete form fn_menu_functional_roles
 
1687                         sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
 
1688                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
1689                         query = localSession.createSQLQuery(sql);
 
1690                         query.executeUpdate();
 
1692                 } catch (Exception e) {
 
1693                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord failed " , e);
 
1694                         throw new Exception("delete Failed"+ e.getMessage());
 
1700         @SuppressWarnings("unchecked")
 
1702         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
 
1703                 List<String> appMenuFunctionsList = null;
 
1705                 EPApp app = getApp(uebkey).get(0);
 
1706                 final Map<String, Long> appParams = new HashMap<>();
 
1707                 appParams.put("appId", app.getId());
 
1708                 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
 
1709                 } catch(Exception e){
 
1710                         logger.error(EELFLoggerDelegate.errorLogger, "Failed getMenuFunctionsList", e);
 
1711                         return appMenuFunctionsList;
 
1713                 return appMenuFunctionsList;