2  * ============LICENSE_START==========================================
 
   4  * ===================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * ===================================================================
 
   8  * Unless otherwise specified, all software contained herein is licensed
 
   9  * under the Apache License, Version 2.0 (the "License");
 
  10  * you may not use this software except in compliance with the License.
 
  11  * You may obtain a copy of the License at
 
  13  *             http://www.apache.org/licenses/LICENSE-2.0
 
  15  * Unless required by applicable law or agreed to in writing, software
 
  16  * distributed under the License is distributed on an "AS IS" BASIS,
 
  17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  18  * See the License for the specific language governing permissions and
 
  19  * limitations under the License.
 
  21  * Unless otherwise specified, all documentation contained herein is licensed
 
  22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 
  23  * you may not use this documentation except in compliance with the License.
 
  24  * You may obtain a copy of the License at
 
  26  *             https://creativecommons.org/licenses/by/4.0/
 
  28  * Unless required by applicable law or agreed to in writing, documentation
 
  29  * distributed under the License is distributed on an "AS IS" BASIS,
 
  30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  31  * See the License for the specific language governing permissions and
 
  32  * limitations under the License.
 
  34  * ============LICENSE_END============================================
 
  36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 
  38 package org.onap.portalapp.portal.service;
 
  40 import java.io.IOException;
 
  41 import java.util.ArrayList;
 
  42 import java.util.HashMap;
 
  43 import java.util.HashSet;
 
  44 import java.util.Iterator;
 
  45 import java.util.LinkedHashMap;
 
  46 import java.util.List;
 
  49 import java.util.SortedSet;
 
  50 import java.util.TreeSet;
 
  51 import java.util.regex.Pattern;
 
  52 import java.util.stream.Collectors;
 
  54 import org.apache.commons.codec.DecoderException;
 
  55 import org.apache.commons.codec.binary.Hex;
 
  56 import org.apache.commons.lang.StringUtils;
 
  57 import org.hibernate.Query;
 
  58 import org.hibernate.Session;
 
  59 import org.hibernate.SessionFactory;
 
  60 import org.hibernate.Transaction;
 
  61 import org.hibernate.criterion.Criterion;
 
  62 import org.hibernate.criterion.Restrictions;
 
  63 import org.json.JSONArray;
 
  64 import org.json.JSONObject;
 
  65 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
 
  66 import org.onap.portalapp.portal.domain.CentralizedApp;
 
  67 import org.onap.portalapp.portal.domain.EPApp;
 
  68 import org.onap.portalapp.portal.domain.EPAppRoleFunction;
 
  69 import org.onap.portalapp.portal.domain.EPRole;
 
  70 import org.onap.portalapp.portal.domain.EPUser;
 
  71 import org.onap.portalapp.portal.domain.EPUserApp;
 
  72 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
 
  73 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
 
  74 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
 
  75 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
 
  76 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
 
  77 import org.onap.portalapp.portal.exceptions.InvalidUserException;
 
  78 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
 
  79 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
 
  80 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
 
  81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
 
  82 import org.onap.portalapp.portal.transport.BulkUploadRoleFunction;
 
  83 import org.onap.portalapp.portal.transport.BulkUploadUserRoles;
 
  84 import org.onap.portalapp.portal.transport.CentralApp;
 
  85 import org.onap.portalapp.portal.transport.CentralRole;
 
  86 import org.onap.portalapp.portal.transport.CentralRoleFunction;
 
  87 import org.onap.portalapp.portal.transport.CentralUser;
 
  88 import org.onap.portalapp.portal.transport.CentralUserApp;
 
  89 import org.onap.portalapp.portal.transport.CentralV2Role;
 
  90 import org.onap.portalapp.portal.transport.CentralV2User;
 
  91 import org.onap.portalapp.portal.transport.CentralV2UserApp;
 
  92 import org.onap.portalapp.portal.transport.EcompUserRoles;
 
  93 import org.onap.portalapp.portal.transport.ExternalAccessPerms;
 
  94 import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail;
 
  95 import org.onap.portalapp.portal.transport.ExternalAccessRole;
 
  96 import org.onap.portalapp.portal.transport.ExternalAccessRolePerms;
 
  97 import org.onap.portalapp.portal.transport.ExternalAccessUser;
 
  98 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
 
  99 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
 
 100 import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction;
 
 101 import org.onap.portalapp.portal.transport.LocalRole;
 
 102 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 
 103 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 
 104 import org.onap.portalapp.portal.utils.PortalConstants;
 
 105 import org.onap.portalapp.util.EPUserUtils;
 
 106 import org.onap.portalsdk.core.domain.Role;
 
 107 import org.onap.portalsdk.core.domain.RoleFunction;
 
 108 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
 109 import org.onap.portalsdk.core.restful.domain.EcompRole;
 
 110 import org.onap.portalsdk.core.restful.domain.EcompUser;
 
 111 import org.onap.portalsdk.core.service.DataAccessService;
 
 112 import org.onap.portalsdk.core.util.SystemProperties;
 
 113 import org.springframework.beans.factory.annotation.Autowired;
 
 114 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
 115 import org.springframework.http.HttpEntity;
 
 116 import org.springframework.http.HttpHeaders;
 
 117 import org.springframework.http.HttpMethod;
 
 118 import org.springframework.http.HttpStatus;
 
 119 import org.springframework.http.ResponseEntity;
 
 120 import org.springframework.stereotype.Service;
 
 121 import org.springframework.transaction.annotation.Transactional;
 
 122 import org.springframework.web.client.HttpClientErrorException;
 
 123 import org.springframework.web.client.RestTemplate;
 
 125 import com.fasterxml.jackson.core.JsonProcessingException;
 
 126 import com.fasterxml.jackson.databind.DeserializationFeature;
 
 127 import com.fasterxml.jackson.databind.ObjectMapper;
 
 128 import com.fasterxml.jackson.databind.type.TypeFactory;
 
 130 @Service("externalAccessRolesService")
 
 131 @EnableAspectJAutoProxy
 
 134 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
 
 136         private static final String APP_ROLE_NAME_PARAM = "appRoleName";
 
 138         private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
 
 140         private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
 
 142         private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
 
 144         private static final String FUNCTION_CODE_PARAMS = "functionCode";
 
 146         private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
 
 148         private static final String OWNER = ".owner";
 
 150         private static final String ADMIN = ".admin";
 
 152         private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
 
 154         private static final String FUNCTION_PIPE = "|";
 
 156         private static final String IS_NULL_STRING = "null";
 
 158         private static final String EXTERNAL_AUTH_PERMS = "perms";
 
 160         private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
 
 162         private static final String IS_EMPTY_JSON_STRING = "{}";
 
 164         private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
 
 166         private static final String APP_ROLE_ID = "appRoleId";
 
 168         private static final String APP_ID = "appId";
 
 170         private static final String PRIORITY = "priority";
 
 172         private static final String ACTIVE = "active";
 
 174         private static final String ROLE_NAME = "name";
 
 176         private static final String ID = "id";
 
 178         private static final String APP_ID_EQUALS = " app_id = ";
 
 180         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
 
 183         private DataAccessService dataAccessService;
 
 186         private EPAppService epAppService;
 
 189         private SessionFactory sessionFactory;
 
 192         EPRoleService ePRoleService;
 
 194         RestTemplate template = new RestTemplate();
 
 197         // These decode values are based on HexDecoder
 
 198         static final String decodeValueOfForwardSlash = "2f";
 
 199         static final String decodeValueOfHiphen = "2d";
 
 200         static final String decodeValueOfStar = "2a";
 
 202         @SuppressWarnings("unchecked")
 
 203         public List<EPRole> getAppRoles(Long appId) throws Exception {
 
 204                 List<EPRole> applicationRoles = null;
 
 205                 final Map<String, Long> appParams = new HashMap<>();
 
 208                                 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
 
 210                                 appParams.put("appId", appId);
 
 211                                 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
 
 213                 } catch (Exception e) {
 
 214                         logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
 
 217                 return applicationRoles;
 
 220         @SuppressWarnings("unchecked")
 
 222         public List<EPApp> getApp(String uebkey) throws Exception {
 
 223                 List<EPApp> app = null;
 
 225                         final Map<String, String> appUebkeyParams = new HashMap<>();
 
 226                         appUebkeyParams.put("appKey", uebkey);
 
 227                         app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
 
 228                         if(!app.isEmpty() && !app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 229                                 throw new InactiveApplicationException("Application:"+app.get(0).getName()+" is Unavailable");
 
 231                 } catch (Exception e) {
 
 232                         logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
 
 239          * It returns  single application role from external auth system 
 
 242          * @return JSON string which contains application role details
 
 245         private String getSingleAppRole(String addRole, EPApp app) throws Exception {
 
 246                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 247                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
 248                 ResponseEntity<String> response = null;
 
 249                 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
 
 250                 response = template.exchange(
 
 251                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
 
 254                                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
 
 255                                 HttpMethod.GET, entity, String.class);
 
 256                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 257                                 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
 
 258                                 response.getStatusCode().value());
 
 259                 return response.getBody();
 
 263         public boolean addRole(Role addRole, String uebkey) throws Exception {
 
 264                 boolean response = false;
 
 265                 ResponseEntity<String> addResponse = null;
 
 266                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 267                 EPApp app = getApp(uebkey).get(0);
 
 268                 String newRole = updateExistingRoleInExternalSystem(addRole, app);
 
 269                 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
 
 270                 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
 
 271                 addResponse = template.exchange(
 
 272                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
 273                                 HttpMethod.POST, entity, String.class);
 
 274                 if (addResponse.getStatusCode().value() == 201) {
 
 276                         logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system  and response code: {} ", addResponse.getStatusCode().value());
 
 278                 if (addResponse.getStatusCode().value() == 406) {
 
 279                         logger.error(EELFLoggerDelegate.errorLogger,
 
 280                                         "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
 
 287          * It deletes record in external auth system
 
 290          * @return JSON String which has status code and response body 
 
 293         private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
 
 294                 ResponseEntity<String> delResponse = null;
 
 295                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 296                 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
 
 297                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
 
 298                 delResponse = template.exchange(
 
 299                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
 
 300                                 HttpMethod.DELETE, entity, String.class);
 
 301                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", delRole, delResponse.getStatusCode().value());
 
 306          * It updates role in external auth system
 
 308          * @param updateExtRole
 
 310          * @return true if success else false
 
 312          *                                      If updateRoleInExternalSystem fails we catch it in logger for detail message
 
 314         @SuppressWarnings("unchecked")
 
 315         private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
 
 316                 boolean response = false;
 
 317                 ObjectMapper mapper = new ObjectMapper();
 
 318                 ResponseEntity<String> deleteResponse = null;
 
 319                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 320                 List<EPRole> epRoleList = null;
 
 321                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
 
 322                                 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
 
 323                         epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
 
 325                         epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
 
 328                 // Assigning functions to global role
 
 329                 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
 
 330                         List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
 
 331                         EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
 
 332                         addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
 
 335                         String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
 
 336                         List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
 
 337                         if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
 
 338                                 JSONObject jsonObj = new JSONObject(appRole);
 
 339                                 JSONArray extRole = jsonObj.getJSONArray("role");
 
 340                                 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
 
 341                                         String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
 
 342                                         Map<String, String> delRoleKeyMapper = new HashMap<>();
 
 343                                         delRoleKeyMapper.put(ROLE_NAME, roleName);
 
 344                                         String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
 
 345                                         deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
 
 346                                         if (deleteResponse.getStatusCode().value() != 200) {
 
 347                                                 throw new ExternalAuthSystemException(deleteResponse.getBody());
 
 349                                         addRole(updateExtRole, app.getUebKey());
 
 351                                         String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
 
 352                                         String name = extRole.getJSONObject(0).getString(ROLE_NAME);
 
 353                                         List<ExternalAccessPerms> list = new ArrayList<>();
 
 354                                         if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
 
 355                                                 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
 
 356                                                 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
 
 357                                                                 .constructCollectionType(List.class, ExternalAccessPerms.class));
 
 359                                         ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class);
 
 360                                         // If role name or role functions are updated then delete
 
 361                                         // record in External System and add new record to avoid
 
 363                                         Boolean existingRoleActive;
 
 364                                         boolean isActiveValueChanged;
 
 365                                         // check role active status
 
 366                                         existingRoleActive = new Boolean(sysRoleList.getActive());
 
 367                                         isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive());
 
 368                                         boolean isRoleNameChanged = false;
 
 369                                         if (!sysRoleList.getName().equals(updateExtRole.getName())) {
 
 370                                                 isRoleNameChanged = true;
 
 371                                                 Map<String, String> delRoleKeyMapper = new HashMap<>();
 
 372                                                 delRoleKeyMapper.put(ROLE_NAME, name);
 
 373                                                 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
 
 374                                                 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
 
 375                                                 if (deleteResponse.getStatusCode().value() != 200) {
 
 376                                                         logger.error(EELFLoggerDelegate.errorLogger,
 
 377                                                                         "updateRoleInExternalSystem:  Failed to delete role in external system due to {} ",
 
 378                                                                         deleteResponse.getBody());
 
 379                                                         throw new ExternalAuthSystemException(deleteResponse.getBody());
 
 381                                                 addRole(updateExtRole, app.getUebKey());
 
 382                                                 // add partner functions to the global role in External Auth System
 
 383                                                 if(!list.isEmpty() && isGlobalRole){
 
 384                                                         addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);       
 
 386                                                 list.removeIf(perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
 
 387                                                 // if role name is changes please ignore the previous functions in External Auth and update with user requested functions
 
 388                                                 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
 
 391                                         boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),
 
 392                                                         String.valueOf(updateExtRole.getPriority()));
 
 393                                         ExternalAccessRole updateRole = new ExternalAccessRole();
 
 394                                         if (!isActiveValueChanged || !checkPriorityStatus || sysRoleList.getId().equals(IS_NULL_STRING)
 
 395                                                         || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
 
 396                                                 String updateDesc = "";
 
 397                                                 List<EPRole> getRole;
 
 398                                                 final Map<String, String> getAppRoleByName =  new HashMap<>();
 
 399                                                 getAppRoleByName.put(APP_ROLE_NAME_PARAM, updateExtRole.getName());
 
 400                                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 401                                                         getRole = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getAppRoleByName,
 
 404                                                         getAppRoleByName.put("appId", String.valueOf(app.getId()));
 
 405                                                         getRole = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
 
 406                                                                         getAppRoleByName, null);
 
 408                                                 Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
 
 409                                                 extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId()));
 
 410                                                 extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName()));
 
 411                                                 extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive()));
 
 412                                                 extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority()));
 
 413                                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 414                                                         extSystemUpdateRoleJsonMapper.put(APP_ID, "null");
 
 415                                                         extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null");
 
 417                                                         extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId()));
 
 418                                                         extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID,
 
 419                                                                         String.valueOf(getRole.get(0).getAppRoleId()));
 
 422                                                 updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
 
 423                                                 updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
 
 424                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 425                                                 updateRole.setDescription(updateDesc);
 
 426                                                 String updateRoleDesc = mapper.writeValueAsString(updateRole);
 
 427                                                 HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
 
 428                                                 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for PUT: {}",
 
 429                                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleDesc);
 
 430                                                 ResponseEntity<String> updatePermsResponse = template.exchange(
 
 431                                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 433                                                                 HttpMethod.PUT, entity, String.class);
 
 434                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 435                                                                 "updateRoleInExternalSystem: Finished updating in External Auth system {} and status code: {} ",
 
 436                                                                 updateRoleDesc, updatePermsResponse.getStatusCode().value());
 
 438                                         if(!isRoleNameChanged) {
 
 439                                                 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
 
 444                                 // It seems like role exists in local DB but not in External
 
 446                                 addRole(updateExtRole, app.getUebKey());
 
 447                                 List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
 
 449                                 if (!roleFunctionListUpdate.isEmpty()) {
 
 450                                         addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
 
 457         private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
 
 458                         List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
 
 460                 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
 
 461                 for (RoleFunction addPerm : roleFunctionListNew) {
 
 462                         updateRoleFunc.put(addPerm.getCode(), addPerm);
 
 464                 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
 
 465                 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
 
 466                 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
 
 467                 // Update permissions in the ExternalAccess System
 
 468                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 469                 if (!list.isEmpty()) {
 
 470                         for (ExternalAccessPerms perm : list) {
 
 471                                 RoleFunction roleFunc =  updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());   
 
 472                                 if (roleFunc==null) {
 
 473                                         RoleFunction roleFuncPipeFilter =  updateRoleFunc.get(perm.getInstance());
 
 474                                         if(roleFuncPipeFilter == null)
 
 475                                         removePermForRole(perm, mapper, name, headers);
 
 477                                 extRolePermMap.put(perm.getInstance(), perm);
 
 478                                 extRolePermMapPipes.put(
 
 479                                                 perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
 
 483                 if (!roleFunctionListNew.isEmpty()) {
 
 484                         for (RoleFunction roleFunc : roleFunctionListNew) {
 
 485                                 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
 
 486                                         ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
 
 488                                                 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
 
 492                                         if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
 
 493                                                 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
 
 503          * Adds function to the role in the external auth system while editing a role or updating new functions to a role 
 
 506         private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
 
 507                         HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
 
 509                 ExternalAccessRolePerms extRolePerms;
 
 510                 ExternalAccessPerms extPerms;
 
 514                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
 
 515                         code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
 516                         type = getFunctionType(roleFunc.getCode());
 
 517                         action = getFunctionAction(roleFunc.getCode());
 
 519                         code = roleFunc.getCode();
 
 520                         type = roleFunc.getCode().contains("menu") ? "menu" : "url";
 
 523                 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
 
 524                 extRolePerms = new ExternalAccessRolePerms(extPerms,
 
 525                                 app.getNameSpace() + "."
 
 526                                                 + updateExtRole.getName().replaceAll(
 
 527                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
 
 529                 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
 530                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
 531                 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
 
 532                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
 
 533                 ResponseEntity<String> addResponse = template.exchange(
 
 534                                 SystemProperties.getProperty(
 
 535                                                 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
 
 536                                 HttpMethod.POST, entity, String.class);
 
 537                 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value()!= 409) {
 
 539                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 540                                         "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
 
 541                                         addResponse.getStatusCode().getReasonPhrase(),
 
 542                                         addResponse.getStatusCode().value());
 
 545                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 546                                         "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
 
 547                                         updateRolePerms, addResponse.getStatusCode().value());
 
 552         private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
 
 553                         EPApp app, Role updateExtRole) throws Exception {
 
 554                 for (ExternalAccessPerms perm : permslist) {
 
 555                         if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
 
 556                                 ExternalAccessRolePerms extAddGlobalRolePerms = null;
 
 557                                 ExternalAccessPerms extAddPerms = null;
 
 558                                 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
 
 559                                 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
 
 560                                                 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
 
 561                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 562                                 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
 
 563                                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 564                                 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
 
 565                                 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
 
 566                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
 568                                         ResponseEntity<String> addResponse = template
 
 569                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 570                                                                         + "role/perm", HttpMethod.POST, entity, String.class);
 
 571                                         if (addResponse.getStatusCode().value() != 201) {
 
 572                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 573                                                                 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
 
 574                                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
 
 576                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 577                                                                 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
 
 578                                                                 addResponse.getStatusCode().value());
 
 580                                 } catch (Exception e) {
 
 581                                         logger.error(EELFLoggerDelegate.errorLogger, "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ",
 
 588         @SuppressWarnings("unchecked")
 
 589         private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
 
 592                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
 
 593                         //GET Permissions from External Auth System
 
 594                         JSONArray extPerms = getExtAuthPermissions(app);
 
 595                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
 
 596                         final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
 
 597                         final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
 
 598                         final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
 
 599                         final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
 
 600                         for (ExternalAccessPermsDetail permDetail : permsDetailList) {
 
 601                                 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
 
 602                                 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
 
 605                         // Add If function does not exists for role in External Auth System
 
 606                         for (RoleFunction roleFunc : roleFunctionListNew) {
 
 607                                 String roleFuncCode = "";
 
 608                                 ExternalAccessPermsDetail permsDetail;
 
 609                                 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
 
 610                                         roleFuncCode = roleFunc.getCode();
 
 611                                         permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
 
 613                                         roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
 614                                         permsDetail = existingPermsWithRoles.get(roleFuncCode);
 
 616                                 if (null == permsDetail.getRoles() || !permsDetail.getRoles()
 
 617                                                 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE + epRoleList.get(0).getName().replaceAll(
 
 618                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
 
 619                                         addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
 
 621                                 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
 
 622                                 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
 
 624                         // Delete functions if exists in External Auth System but not in incoming request
 
 625                         final Map<String, Long> epAppRoleFuncParams =  new HashMap<>();
 
 626                         epAppRoleFuncParams.put("requestedAppId", app.getId());
 
 627                         epAppRoleFuncParams.put("roleId",updateExtRole.getId());
 
 628                         List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
 
 629                         for(GlobalRoleWithApplicationRoleFunction globalRoleFunc: globalRoleFunctionList){
 
 630                                 String globalRoleFuncWithoutPipes = "";
 
 631                                 RoleFunction roleFunc = null;
 
 632                                 if(globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
 
 633                                         globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
 
 634                                         roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
 
 636                                         globalRoleFuncWithoutPipes  = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
 
 637                                         roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
 
 639                                 if(roleFunc == null){
 
 640                                         ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
 
 641                                         ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), permDetailFromMap.getAction());
 
 642                                         String roleName = portalAppInfo.getNameSpace()+"."+globalRoleFunc.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
 
 643                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 644                                         removePermForRole(perm, mapper, roleName, headers);
 
 647                         logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
 
 648                 } catch (Exception e) {
 
 649                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed",e);
 
 654         private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, ObjectMapper mapper, EPApp app,
 
 655                         EPApp portalAppInfo) throws Exception {
 
 657                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
 
 658                         ExternalAccessRolePerms extAddRolePerms = null;
 
 659                         ExternalAccessPerms extAddPerms = null;
 
 660                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 664                                 if (addFunction.getCode().contains(FUNCTION_PIPE)) {
 
 665                                         code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
 
 666                                         type = getFunctionType(addFunction.getCode());
 
 667                                         action = getFunctionAction(addFunction.getCode());
 
 669                                         code = addFunction.getCode();
 
 670                                         type = addFunction.getCode().contains("menu") ? "menu" : "url";
 
 673                                 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
 
 674                                 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
 
 675                                                 portalAppInfo.getNameSpace() + "." + globalRole.getName().replaceAll(
 
 676                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 677                                 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
 
 678                                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
 679                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
 
 680                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
 681                                 ResponseEntity<String> addResponse = template
 
 682                                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 683                                                                 + "role/perm", HttpMethod.POST, entity, String.class);
 
 684                                 if (addResponse.getStatusCode().value() != 201) {
 
 685                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 686                                                         "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
 
 687                                                         addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
 
 689                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 690                                                         "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
 
 691                                                         addResponse.getStatusCode().value());
 
 693                         logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
 
 695                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed",e);
 
 702          * It adds functions to the role in external auth system 
 
 704          * @param updateExtRole
 
 705          * @param addPermsMapper
 
 707          * @return true if success else false
 
 710         private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app)
 
 712                 boolean response = false;
 
 713                 ExternalAccessRolePerms extAddRolePerms = null;
 
 714                 ExternalAccessPerms extAddPerms = null;
 
 715                 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
 
 716                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 717                 for (RoleFunction roleFunc : roleFunctionListAdd) {
 
 721                         if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
 
 722                                 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
 723                                 type = getFunctionType(roleFunc.getCode());
 
 724                                 action = getFunctionAction(roleFunc.getCode());
 
 726                                 code = roleFunc.getCode();
 
 727                                 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
 
 730                         extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
 
 731                         extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
 
 732                                         app.getNameSpace() + "." + updateExtRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 733                         String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
 
 734                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
 735                         logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
 
 736                         ResponseEntity<String> addResponse = template.exchange(
 
 737                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
 
 738                                         HttpMethod.POST, entity, String.class);
 
 739                         if (addResponse.getStatusCode().value() != 201) {
 
 741                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 742                                                 "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
 
 743                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
 
 746                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value());
 
 754          * It converts list of functions in updateExtRole parameter to the RoleFunction object
 
 756          * @param updateExtRole
 
 757          * @return list of functions 
 
 759         @SuppressWarnings("unchecked")
 
 760         private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
 
 761                 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
 
 762                 List<RoleFunction> roleFunctionList = new ArrayList<>();
 
 763                 ObjectMapper roleFuncMapper = new ObjectMapper();
 
 764                 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
 
 765                 while (itetaror.hasNext()) {
 
 766                         Object nextValue = itetaror.next();
 
 767                         RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
 
 768                         roleFunctionList.add(roleFunction);
 
 770                 return roleFunctionList.stream().distinct().collect(Collectors.toList());
 
 774          * It delete permissions/functions in the external auth system
 
 780          * @throws JsonProcessingException 
 
 783         private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
 
 784                         throws ExternalAuthSystemException, JsonProcessingException {
 
 785                 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
 
 786                 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
 
 788                 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
 
 789                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
 
 790                 ResponseEntity<String> deletePermResponse = template
 
 791                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
 
 792                                                 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
 
 793                 if (deletePermResponse.getStatusCode().value() != 200) {
 
 794                         throw new ExternalAuthSystemException(deletePermResponse.getBody());
 
 796                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
 
 797                                 permDetails, deletePermResponse.getStatusCode().value());
 
 798                 } catch(Exception e){
 
 799                         if(e.getMessage().contains("404")){
 
 800                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", permDetails, e.getMessage());                               
 
 808          * It will create new role in the External Auth System
 
 812          * @return true if successfully added in the system else false
 
 814          *             If fails to add role in the system
 
 816         private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception, HttpClientErrorException {
 
 818                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 819                 ObjectMapper mapper = new ObjectMapper();
 
 820                 String addNewRole = "";
 
 821                 ExternalAccessRole extRole = new ExternalAccessRole();
 
 822                 String addDesc = null;
 
 823                 Map<String, String> extSystemJsonMapper = new LinkedHashMap<>();
 
 824                 extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId()));
 
 825                 extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName()));
 
 826                 extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive()));
 
 827                 extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority()));
 
 828                 extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId()));
 
 829                 extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId()));
 
 830                 addDesc = mapper.writeValueAsString(extSystemJsonMapper);
 
 831                 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 832                 extRole.setDescription(addDesc);
 
 833                 addNewRole = mapper.writeValueAsString(extRole);
 
 834                 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
 
 835                 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
 
 836                 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
 
 837                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
 838                                 HttpMethod.POST, postEntity, String.class);
 
 839                         if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
 
 840                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 841                                                 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
 
 842                                                 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
 
 844                 }catch(HttpClientErrorException ht){
 
 845                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ newRole.get(0).getId(), null);
 
 846                         logger.error(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}",
 
 848                         throw new HttpClientErrorException(ht.getStatusCode());
 
 854          * It updates existing role in the External Auth System
 
 857          *            It Contains role information
 
 859          * @return string which is formatted to match with the external auth system
 
 860          * @throws JsonProcessingException
 
 862         private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
 
 863                 ObjectMapper mapper = new ObjectMapper();
 
 864                 String addNewRole = "";
 
 865                 ExternalAccessRole extRole = new ExternalAccessRole();
 
 866                 List<EPRole> role = null;
 
 867                 String addDesc = null;
 
 868                 Map<String, String> extSystemUpdateRole = new LinkedHashMap<>();
 
 869                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 870                         role = getPortalAppRoleInfo(addRole.getId());
 
 872                         role = getPartnerAppRoleInfo(addRole.getId(), app);
 
 874                 extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId()));
 
 875                 extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName()));
 
 876                 extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive()));
 
 877                 extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority()));
 
 878                 extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId()));
 
 879                 extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId()));
 
 880                 addDesc = mapper.writeValueAsString(extSystemUpdateRole);
 
 881                 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 882                 extRole.setDescription(addDesc);
 
 883                 addNewRole = mapper.writeValueAsString(extRole);
 
 888          * It create a role in the external auth system and then in our local 
 
 892          * @return true else false
 
 895         @SuppressWarnings("unchecked")
 
 896         @Transactional(rollbackFor = Exception.class)
 
 897         private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {                
 
 898                 boolean result = false;
 
 899                 EPRole epRole = null;
 
 900                 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
 
 901                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
 
 902                 ObjectMapper mapper = new ObjectMapper();
 
 903                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
 
 904                 while (itetaror.hasNext()) {
 
 905                         Object nextValue = itetaror.next();
 
 906                         RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
 
 907                         roleFunctionListNew.add(roleFunction);
 
 909                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
 
 911                         if (addRoleInDB.getId() == null) { // check if it is new role
 
 912                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
 913                                         checkIfRoleExitsInExternalSystem(addRoleInDB, app);
 
 915                                 EPRole epRoleNew = new EPRole();
 
 916                                 epRoleNew.setActive(addRoleInDB.getActive());
 
 917                                 epRoleNew.setName(addRoleInDB.getName());
 
 918                                 epRoleNew.setPriority(addRoleInDB.getPriority());
 
 919                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 920                                         epRoleNew.setAppId(null);
 
 922                                         epRoleNew.setAppId(app.getId());
 
 924                                 dataAccessService.saveDomainObject(epRoleNew, null);
 
 925                                 List<EPRole> getRoleCreated = null;
 
 926                                 final Map<String, String> epAppRoleParams =  new HashMap<>();
 
 927                                 final Map<String, String> epAppPortalRoleParams =  new HashMap<>();
 
 928                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 929                                         epAppRoleParams.put("appId", String.valueOf(app.getId()));
 
 930                                         epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
 
 931                                         List<EPRole> roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
 
 932                                         EPRole epUpdateRole = roleCreated.get(0);
 
 933                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
 
 934                                         dataAccessService.saveDomainObject(epUpdateRole, null);
 
 935                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
 
 937                                         epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
 
 938                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null);
 
 940                                 // Add role in External Auth system
 
 941                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
 942                                         addNewRoleInExternalSystem(getRoleCreated, app);
 
 944                         } else { // if role already exists then update it
 
 945                                 EPRole globalRole = null;
 
 946                                 List<EPRole> applicationRoles;
 
 947                                 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
 
 948                                 boolean isGlobalRole = false;
 
 949                                 if (!globalRoleList.isEmpty()) {
 
 950                                         EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
 
 957                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
 
 958                                                 || (globalRole != null && app.getId() != globalRole.getAppId())) {
 
 959                                         applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
 
 961                                         applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
 
 963                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
 964                                         updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
 
 965                                         // Add all user to the re-named role in external auth system
 
 966                                         if (!applicationRoles.isEmpty()
 
 967                                                         && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
 
 968                                                 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
 
 969                                                                 addRoleInDB.getName());
 
 972                                 deleteRoleFunction(app, applicationRoles);
 
 973                                 if (!applicationRoles.isEmpty()) {
 
 974                                         epRole = applicationRoles.get(0);
 
 975                                         epRole.setName(addRoleInDB.getName());
 
 976                                         epRole.setPriority(addRoleInDB.getPriority());
 
 977                                         epRole.setActive(addRoleInDB.getActive());
 
 978                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 979                                                 epRole.setAppId(null);
 
 980                                                 epRole.setAppRoleId(null);
 
 981                                         } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
 
 982                                                         && applicationRoles.get(0).getAppRoleId() == null) {
 
 983                                                 epRole.setAppRoleId(epRole.getId());
 
 985                                         dataAccessService.saveDomainObject(epRole, null);
 
 987                                 Long roleAppId = null;
 
 988                                 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
 
 989                                         roleAppId = PortalConstants.PORTAL_APP_ID;
 
 990                                 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
 
 993                 } catch (Exception e) {
 
 994                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
 
1002          * It validates whether role exists in external auth system
 
1009         private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
 
1010                 getNameSpaceIfExists(app);
 
1011                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1012                 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
 
1013                 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
 
1014                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
1015                 ResponseEntity<String> checkRoleInExternalSystem = template
 
1016                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
 
1017                                                 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
 
1018                 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
 
1019                         logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
 
1020                         throw new ExternalAuthSystemException(" Role already exists in external system");
 
1025          * It saves list of functions to the role in portal
 
1027          * @param roleFunctionListNew
 
1029          * @param applicationRoles
 
1032         @SuppressWarnings("unchecked")
 
1033         private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
 
1035                 final Map<String, String> getAppFunctionParams = new HashMap<>(); 
 
1037                 for (RoleFunction roleFunc : roleFunctionListNew) {
 
1038                         String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
1039                         EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
 
1040                         appRoleFunc.setAppId(app.getId());
 
1041                         appRoleFunc.setRoleId(applicationRoles.get(0).getId());
 
1042                         appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
 
1043                         getAppFunctionParams.put("appId", String.valueOf(app.getId()));
 
1044                         getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
 
1045                         // query to check if function code has pipes
 
1046                         List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
 
1047                         if(roleFunction.isEmpty()){
 
1048                                 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
 
1049                                 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
 
1051                         if(roleFunction.size() > 1){
 
1052                                 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
 
1053                                 appRoleFunc.setCode(getExactFunctionCode.getCode());
 
1055                                 appRoleFunc.setCode(roleFunction.get(0).getCode());
 
1058                         dataAccessService.saveDomainObject(appRoleFunc, null);
 
1064          * It filters the app functions which starts with similar name in the result set
 
1067          * @param roleFunction
 
1068          * @return CentralRoleFunction 
 
1070         private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
 
1071                 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>(); 
 
1072                 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>(); 
 
1073                 CentralV2RoleFunction getExactFunctionCode = null;
 
1074                 for(CentralV2RoleFunction cenRoleFunction : roleFunction){
 
1075                         appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
 
1076                         appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
 
1078                 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
 
1079                 if(getExactFunctionCode == null){
 
1080                         getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
 
1082                 return getExactFunctionCode;
 
1086          * It deletes all EPAppRoleFunction records in the portal
 
1091         @SuppressWarnings("unchecked")
 
1092         private void deleteRoleFunction(EPApp app, List<EPRole> role) {
 
1093                 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
 
1094                 appRoleFuncsParams.put("appId", app.getId());
 
1095                 appRoleFuncsParams.put("roleId", role.get(0).getId());
 
1096                 List<EPAppRoleFunction> appRoleFunctionList =  dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
 
1097                 if (!appRoleFunctionList.isEmpty()) {
 
1098                         for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
 
1099                                 dataAccessService.deleteDomainObject(approleFunction, null);
 
1105         @SuppressWarnings("unchecked")
 
1106         public List<EPUser> getUser(String loginId) throws InvalidUserException{
 
1107                 final Map<String, String> userParams = new HashMap<>();
 
1108                 userParams.put("org_user_id", loginId);
 
1109                 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
 
1110                 if (userList.isEmpty()) {
 
1111                         throw new InvalidUserException("User not found");
 
1117         public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
 
1118                 final Map<String, String> params = new HashMap<>();
 
1119                 List<EPUser> userList = null;
 
1120                 CentralV2User cenV2User = null;
 
1121                 String result = null;
 
1123                         params.put("orgUserIdValue", loginId);
 
1124                         List<EPApp> appList = getApp(uebkey);
 
1125                         if (!appList.isEmpty()) {
 
1126                                 userList = getUser(loginId);
 
1127                                 if (!userList.isEmpty()) {
 
1128                                         ObjectMapper mapper = new ObjectMapper();
 
1129                                         cenV2User = getV2UserAppRoles(loginId, uebkey);
 
1130                                         result = mapper.writeValueAsString(cenV2User);
 
1131                                 } else if (userList.isEmpty()) {
 
1132                                         throw new InvalidUserException("User not found");
 
1135                                 throw new InactiveApplicationException("Application not found");
 
1137                 } catch (Exception e) {
 
1138                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
 
1145         public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
 
1146                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
 
1147                 List<CentralV2Role> roleList = new ArrayList<>();
 
1148                 final Map<String, Long> params = new HashMap<>();
 
1150                         List<EPApp> app = getApp(uebkey);
 
1151                         List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
 
1152                         roleList = createCentralRoleObject(app, appRolesList, roleList, params);
 
1153                         if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
 
1154                             List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
 
1155                                 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
 
1156                             List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
 
1157                                 if (!globalRolesList.isEmpty()) {
 
1158                                         for (EPRole eprole : globalRolesList) {
 
1159                                                 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
 
1160                                                 portalsGlobalRolesFinlaList.add(cenRole);
 
1162                                         roleList.addAll(globalRoleList);
 
1163                                         for (CentralV2Role role : portalsGlobalRolesFinlaList) {
 
1164                                                 CentralV2Role result = roleList.stream()
 
1165                                                                         .filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
 
1170                                         for (EPRole role : globalRolesList) {
 
1171                                                 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
 
1172                                                 roleList.add(cenRole);
 
1176                 } catch (Exception e) {
 
1177                         logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
 
1180                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
 
1181                 return roleList.stream().distinct().collect(Collectors.toList());
 
1184         @SuppressWarnings("unchecked")
 
1186         public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
 
1187                 EPApp app = getApp(uebkey).get(0);
 
1188                 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
 
1189                 final Map<String, Long> params = new HashMap<>();
 
1190                 params.put(APP_ID, app.getId());
 
1191                 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
 
1192                 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
 
1193                         String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
 
1194                         String type = getFunctionType(roleFuncItem.getCode());
 
1195                         String action = getFunctionAction(roleFuncItem.getCode());
 
1196                         roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
 
1197                         roleFuncItem.setType(type);
 
1198                         roleFuncItem.setAction(action);
 
1199                         finalRoleList.add(roleFuncItem);
 
1201                 return finalRoleList;
 
1206          * It return function action
 
1208          * @param roleFuncItem
 
1209          * @return String action
 
1211         private String getFunctionAction(String roleFuncItem) {
 
1212                 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
 
1213                                 : EcompPortalUtils.getFunctionAction(roleFuncItem);
 
1218          * It check function code has any pipes, if found return function type
 
1220          * @param roleFuncItem
 
1222          * @return function type
 
1224         private String getFunctionType(String roleFuncItem) {
 
1226                 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
 
1227                                 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
 
1229                 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
 
1230                                 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
 
1231                                 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
 
1233                 } else if (roleFuncItem.contains(FUNCTION_PIPE)
 
1234                                 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
 
1235                         type = EcompPortalUtils.getFunctionType(roleFuncItem);
 
1242          * It check whether function code has no pipes and no url string in it
 
1244          * @param roleFuncItem
 
1245          * @return true or false
 
1247         private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
 
1248                 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
 
1253          * It check whether function code has pipes and url string in it  
 
1255          * @param roleFuncItem
 
1256          * @return true or false
 
1258         private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
 
1259                 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
 
1264          * It check whether function code has no pipes and has url string in it 
 
1266          * @param roleFuncItem
 
1267          * @return true or false
 
1269         private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
 
1270                 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
 
1274          * It returns user detail information which is deep copy of EPUser.class object
 
1282         @SuppressWarnings("unchecked")
 
1283         private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
 
1285                 final Map<String, Long> params = new HashMap<>();
 
1286                 CentralV2User userAppList = new CentralV2User();
 
1287                 CentralV2User user1 = null;
 
1289                         userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
 
1290                         for (EPUserApp userApp : userAppSet) {
 
1291                                 if (userApp.getRole().getActive()) {
 
1292                                         EPApp epApp = userApp.getApp();
 
1293                                         String globalRole = userApp.getRole().getName().toLowerCase();
 
1294                                         if (((epApp.getId().equals(app.getId()))
 
1295                                                         && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
 
1296                                                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
 
1297                                                                         && (globalRole.toLowerCase().startsWith("global_")))) {
 
1298                                                 CentralV2UserApp cua = new CentralV2UserApp();
 
1299                                                 cua.setUserId(null);
 
1300                                                 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
 
1301                                                                 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
 
1302                                                                 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
 
1303                                                                 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
 
1304                                                                 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
 
1305                                                                 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
 
1306                                                                 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
 
1307                                                                 epApp.getUebTopicName());
 
1309                                                 params.put("roleId", userApp.getRole().getId());
 
1310                                                 params.put(APP_ID, userApp.getApp().getId());
 
1311                                                 CentralV2Role centralRole;
 
1312                                                 List<EPRole> globalRoleList;
 
1313                                                 globalRoleList = getGlobalRolesOfPortal();
 
1314                                                 EPRole result = globalRoleList.stream().filter(x -> userApp.getRole().getId().equals(x.getId()))
 
1315                                                                 .findAny().orElse(null);
 
1316                                                 if (result != null && userApp.getApp().getId() != app.getId()) {
 
1317                                                         userApp.getRole().setId(result.getId());
 
1318                                                         centralRole = getGlobalRoleForRequestedApp(app.getId(), userApp.getRole().getId());
 
1319                                                         cua.setRole(centralRole);
 
1321                                                         List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
 
1322                                                                         .executeNamedQuery("getAppRoleFunctionList", params, null);
 
1323                                                         SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
 
1324                                                         for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
 
1325                                                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
1326                                                                 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
 
1327                                                                                 functionCode, roleFunc.getName(), null, null);
 
1328                                                                 roleFunctionSet.add(cenRoleFunc);
 
1330                                                         Long userRoleId = null;
 
1331                                                         if (globalRole.toLowerCase().startsWith("global_")
 
1332                                                                         && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1333                                                                 userRoleId = userApp.getRole().getId();
 
1335                                                                 userRoleId = userApp.getRole().getAppRoleId();
 
1337                                                         CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
 
1338                                                                         userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
 
1339                                                                         userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
 
1340                                                                         userApp.getRole().getName(), userApp.getRole().getActive(),
 
1341                                                                         userApp.getRole().getPriority(), roleFunctionSet, null, null);
 
1342                                                         cua.setRole(cenRole);
 
1344                                                 userAppList.getUserApps().add(cua);
 
1349                         user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
 
1350                                         userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
 
1351                                         userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
 
1352                                         userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
 
1353                                         userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
 
1354                                         userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
 
1355                                         userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
 
1356                                         userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
 
1357                                         userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
 
1358                                         userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
 
1359                                         userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
 
1360                                         userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
 
1361                                         userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
 
1362                                         userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
 
1363                                         userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
 
1364                 } catch (Exception e) {
 
1365                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
 
1372         public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
 
1373                 final Map<String, Long> params = new HashMap<>();
 
1374                 List<CentralV2Role> roleList = new ArrayList<>();
 
1375                 CentralV2Role cenRole = new CentralV2Role();
 
1376                 List<EPRole> roleInfo = null;
 
1377                 List<EPApp> app = null;
 
1379                         app = getApp(uebkey);
 
1380                         if (app.isEmpty()) {
 
1381                                 throw new InactiveApplicationException("Application not found");
 
1383                         if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
 
1384                                 List<EPRole> globalRoleList = new ArrayList<>();
 
1385                                 globalRoleList = getGlobalRolesOfPortal();
 
1386                                 if (globalRoleList.size() > 0) {
 
1387                                         EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
 
1390                                                 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
 
1393                         if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1394                                 roleInfo = getPortalAppRoleInfo(roleId);
 
1396                                 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
 
1398                         roleList = createCentralRoleObject(app, roleInfo, roleList, params);
 
1399                         if (roleList.isEmpty()) {
 
1403                 } catch (Exception e) {
 
1404                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
 
1408                 return roleList.get(0);
 
1411         @SuppressWarnings("unchecked")
 
1412         private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
 
1413                 List<EPRole> roleInfo;
 
1414                 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
 
1415                 getPartnerAppRoleParams.put("appRoleId", roleId);
 
1416                 getPartnerAppRoleParams.put("appId", app.getId());                              
 
1417                 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
 
1418                 if(roleInfo.isEmpty()) {
 
1419                         getPartnerAppRoleParams.put("appRoleId", roleId);
 
1420                         roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
 
1425         @SuppressWarnings("unchecked")
 
1426         private List<EPRole> getPortalAppRoleInfo(Long roleId) {
 
1427                 List<EPRole> roleInfo;
 
1428                 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
 
1429                 getPortalAppRoleParams.put("roleId", roleId);
 
1430                 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
 
1436          * It returns list of app roles along with role functions and which went through deep copy
 
1443          * @throws DecoderException 
 
1445         @SuppressWarnings("unchecked")
 
1446         private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
 
1447                         List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
 
1448                 for (EPRole role : roleInfo) {
 
1449                         params.put("roleId", role.getId());
 
1450                         params.put(APP_ID, app.get(0).getId());
 
1451                         List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
 
1453                         SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
 
1454                         for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
 
1455                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
1456                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
 
1457                                 String type = getFunctionType(roleFunc.getCode());
 
1458                                 String action = getFunctionAction(roleFunc.getCode());
 
1459                                 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
 
1460                                                 roleFunc.getName(), null, type, action, null);
 
1461                                 roleFunctionSet.add(cenRoleFunc);
 
1463                         SortedSet<CentralV2Role> childRoles = new TreeSet<>();
 
1464                         SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
 
1465                         CentralV2Role cenRole = null;
 
1466                         if (role.getAppRoleId() == null) {
 
1467                                 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
 
1468                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
 
1469                                                 roleFunctionSet, childRoles, parentRoles);
 
1471                                 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
 
1472                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
 
1473                                                 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
 
1475                         roleList.add(cenRole);
 
1480         @SuppressWarnings("unchecked")
 
1482         public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
 
1483                 if (functionCode.contains("|"))
 
1484                         functionCode = EcompPortalUtils.getFunctionCode(functionCode);
 
1485                 functionCode = encodeFunctionCode(functionCode);
 
1486                 CentralV2RoleFunction roleFunc = null;
 
1487                 EPApp app = getApp(uebkey).get(0);
 
1488                 List<CentralV2RoleFunction> getRoleFuncList = null;
 
1489                 final Map<String, String> params = new HashMap<>();
 
1491                         params.put(FUNCTION_CODE_PARAMS, functionCode);
 
1492                         params.put(APP_ID, String.valueOf(app.getId()));
 
1493                         getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
 
1494                         if (getRoleFuncList.isEmpty()) {
 
1497                                 if (getRoleFuncList.size() > 1) {
 
1498                                         CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(functionCode, getRoleFuncList);
 
1499                                         if(cenV2RoleFunction == null)
 
1501                                         roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
 
1503                                         roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
 
1506                 } catch (Exception e) {
 
1507                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
 
1513         private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
 
1514                 CentralV2RoleFunction roleFunc;
 
1515                 String functionCodeFormat = getRoleFuncList.getCode();
 
1516                 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
 
1517                         String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
 
1518                         String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
 
1519                         String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
 
1520                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
 
1521                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
 
1522                                         getRoleFuncList.getEditUrl());
 
1524                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
 
1525                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(),
 
1526                                         getRoleFuncList.getEditUrl());
 
1531         @SuppressWarnings("unchecked")
 
1533         public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
 
1534                 boolean saveOrUpdateFunction = false;
 
1536                         domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
 
1537                         final Map<String, String> functionParams = new HashMap<>();
 
1538                         functionParams.put("appId", String.valueOf(app.getId()));
 
1539                         List<CentralV2RoleFunction> appRoleFuncWithPipe = new ArrayList<>();
 
1540                         // If request coming from portal application we use type, instance/code and action to fetch record
 
1541                         if(domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null){
 
1542                                 functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getType()+FUNCTION_PIPE
 
1543                                                 +domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
 
1544                                 appRoleFuncWithPipe =  dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, functionParams, null);
 
1545                                 if(appRoleFuncWithPipe.isEmpty()){
 
1546                                         functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getCode());
 
1547                                         appRoleFuncWithPipe =  dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, functionParams, null);
 
1550                         // If request coming from SDK applications we use just function code to fetch record
 
1552                                 functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getCode());
 
1554                         CentralV2RoleFunction appFunctionCode = null;
 
1555                         if(!appRoleFuncWithPipe.isEmpty()){
 
1556                                 // Make sure we extract correct record if similar records are found as query uses like condition 
 
1557                            appFunctionCode = appFunctionListFilter(domainCentralRoleFunction.getCode(), appRoleFuncWithPipe);   
 
1558                            if(appFunctionCode == null){
 
1559                                    appFunctionCode = domainCentralRoleFunction;
 
1562                                 appFunctionCode = domainCentralRoleFunction;
 
1564                         appFunctionCode.setName(domainCentralRoleFunction.getName());
 
1565                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1566                                 addRoleFunctionInExternalSystem(appFunctionCode, app);                  
 
1568                         if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
 
1569                                 appFunctionCode.setCode(domainCentralRoleFunction.getType()+
 
1570                                         FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
 
1572                         appFunctionCode.setAppId(app.getId());
 
1573                         dataAccessService.saveDomainObject(appFunctionCode, null);
 
1574                         saveOrUpdateFunction = true;
 
1575                 } catch (Exception e) {
 
1576                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
 
1579                 return saveOrUpdateFunction;
 
1583          * It creates application permission in external auth system
 
1585          * @param domainCentralRoleFunction
 
1589         private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
 
1591                 ObjectMapper mapper = new ObjectMapper();
 
1592                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
 
1593                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); 
 
1595                 String instance = "";
 
1597                 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
 
1598                         type =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType(); 
 
1599                         instance =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ?  EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
 
1600                         action =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
 
1602                         type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
 
1603                         instance = domainCentralRoleFunction.getCode();
 
1606                 // get Permissions from External Auth System
 
1607                 JSONArray extPermsList = getExtAuthPermissions(app);
 
1608                 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
 
1609                 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
 
1610                 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
 
1611                 if (!checkIfFunctionsExits) {
 
1613                                 extPerms.setAction(action);
 
1614                                 extPerms.setInstance(instance);
 
1615                                 extPerms.setType(app.getNameSpace() + "." + type);
 
1616                                 extPerms.setDescription(domainCentralRoleFunction.getName());
 
1617                                 String addFunction = mapper.writeValueAsString(extPerms);
 
1618                                 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
 
1619                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
 
1620                                 ResponseEntity<String> addPermResponse= template.exchange(
 
1621                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
 
1622                                                 HttpMethod.POST, entity, String.class);
 
1623                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
 
1624                         } catch(HttpClientErrorException e){
 
1625                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
 
1626                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1628                         }catch (Exception e) {
 
1629                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
 
1635                                 extPerms.setAction(action);
 
1636                                 extPerms.setInstance(instance);
 
1637                                 extPerms.setType(app.getNameSpace() + "." + type);
 
1638                                 extPerms.setDescription(domainCentralRoleFunction.getName());
 
1639                                 String updateRoleFunction = mapper.writeValueAsString(extPerms);
 
1640                                 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
 
1641                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
 
1642                                 ResponseEntity<String> updatePermResponse = template.exchange(
 
1643                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
 
1644                                                 HttpMethod.PUT, entity, String.class);
 
1645                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
 
1646                         } catch(HttpClientErrorException e){
 
1647                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
 
1648                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1650                         } catch (Exception e) {
 
1651                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
 
1657         @SuppressWarnings("unchecked")
 
1659         @Transactional(rollbackFor = Exception.class)
 
1660         public boolean deleteCentralRoleFunction(String code, EPApp app) {
 
1661                 boolean deleteFunctionResponse = false;
 
1663                         final Map<String, String> params = new HashMap<>();
 
1664                         params.put(FUNCTION_CODE_PARAMS, code);
 
1665                         params.put(APP_ID, String.valueOf(app.getId()));
 
1666                         List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
 
1667                                         .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
 
1668                         CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
 
1669                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1670                                 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
 
1671                                 // Delete role function dependency records
 
1672                                 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
 
1674                         dataAccessService.deleteDomainObject(appFunctionCode, null);
 
1675                         deleteFunctionResponse = true;
 
1676                 } catch (Exception e) {
 
1677                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
 
1679                 return deleteFunctionResponse;
 
1683          * It deletes app function record in portal 
 
1688         private void deleteAppRoleFunctions(String code, EPApp app) {
 
1689                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
 
1690                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
 
1695          * It deletes permission in the external auth system  
 
1697          * @param domainCentralRoleFunction
 
1701         private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
 
1704                         ObjectMapper mapper = new ObjectMapper();
 
1705                         ExternalAccessPerms extPerms = new ExternalAccessPerms();
 
1706                         String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
 
1707                         String checkType = getFunctionType(domainCentralRoleFunction.getCode());
 
1708                         String actionValue = getFunctionAction(domainCentralRoleFunction.getCode());
 
1709                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1710                         extPerms.setAction(actionValue);
 
1711                         extPerms.setInstance(instanceValue);
 
1712                         extPerms.setType(app.getNameSpace() + "." + checkType);
 
1713                         extPerms.setDescription(domainCentralRoleFunction.getName());
 
1714                         String deleteRoleFunction = mapper.writeValueAsString(extPerms);
 
1715                         HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
 
1716                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
 
1717                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
 
1718                         ResponseEntity<String> delPermResponse = template
 
1719                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1720                                                         + "perm?force=true", HttpMethod.DELETE, entity, String.class);
 
1721                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1722                                         "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
 
1723                                         deleteRoleFunction, delPermResponse.getStatusCode().value());
 
1724                 } catch(HttpClientErrorException e){
 
1725                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
 
1726                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1727                 } catch (Exception e) {
 
1728                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
 
1729                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1730                                                 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
 
1733                                 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
 
1739         public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
 
1740                 boolean response = false;
 
1741                 String message = "";
 
1743                         EPApp app = getApp(uebkey).get(0);
 
1744                         addRoleInEcompDB(saveRole, app);
 
1746                 } catch (Exception e) {
 
1747                         message = e.getMessage();
 
1748                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
 
1750                 return new ExternalRequestFieldsValidator(response,message);
 
1753         @SuppressWarnings("unchecked")
 
1755         public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
 
1756                 Session localSession = sessionFactory.openSession();
 
1757                 Transaction transaction = null;
 
1758                 boolean result = false;
 
1760                         List<EPRole> epRoleList = null;
 
1761                         EPApp app = getApp(uebkey).get(0);
 
1762                         final Map<String, String> deleteRoleParams = new HashMap<>();
 
1763                         deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
 
1764                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1765                                 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
 
1767                                 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
 
1768                                 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
 
1770                         if (!epRoleList.isEmpty()) {
 
1771                                 transaction = localSession.beginTransaction();
 
1772                                 // Delete app role functions before deleting role
 
1773                                 deleteRoleFunction(app, epRoleList);
 
1774                                 if (app.getId() == 1) {
 
1775                                         // Delete fn_user_ role
 
1776                                         dataAccessService.deleteDomainObjects(EPUserApp.class,
 
1777                                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
 
1778                                         boolean isPortalRequest = false;
 
1779                                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
 
1781                                 deleteRoleInExternalAuthSystem(epRoleList, app);
 
1782                                 transaction.commit();
 
1783                                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
 
1784                                 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
 
1787                 } catch (Exception e) {
 
1788                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
 
1791                         localSession.close();
 
1798          * It deletes role for application in external auth system 
 
1800          * @param epRoleList contains role information
 
1801          * @param app contains application information
 
1804         private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
 
1805                 ResponseEntity<String> deleteResponse;
 
1806                 ResponseEntity<String> res = getNameSpaceIfExists(app);
 
1807                 if (res.getStatusCode() == HttpStatus.OK) {
 
1808                 // Delete Role in External System
 
1809                 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
 
1810                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
 
1811                 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
 
1812                 if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
 
1813                         EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
 
1814                         logger.error(EELFLoggerDelegate.errorLogger,
 
1815                                         "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
 
1816                                         deleteResponse.getBody());
 
1818                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1819                                 "deleteRoleForApplication: about to commit the transaction");
 
1825          * It deletes application user role in external auth system
 
1832         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
 
1833                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1834                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
1835                 getNameSpaceIfExists(app);
 
1836                 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
1837                 ResponseEntity<String> getResponse = template
 
1839                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
 
1842                                                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
 
1843                                                                 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
 
1844                                                 HttpMethod.GET, entity, String.class);
 
1845                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
 
1846                 if (getResponse.getStatusCode().value() != 200) {
 
1847                         throw new ExternalAuthSystemException(getResponse.getBody());
 
1849                 String res = getResponse.getBody();
 
1850                 if (!res.equals(IS_EMPTY_JSON_STRING)) {
 
1851                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
 
1852                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
1853                         ResponseEntity<String> deleteResponse = template
 
1855                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1856                                                                         + "userRole/" + LoginId
 
1858                                                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
 
1859                                                                         + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
 
1860                                                         HttpMethod.DELETE, userRoleentity, String.class);
 
1861                         if (deleteResponse.getStatusCode().value() != 200) {
 
1862                                 throw new ExternalAuthSystemException("Failed to delete user role");
 
1864                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
 
1868         @SuppressWarnings("unchecked")
 
1870         public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
 
1871                 List<CentralV2Role> roleList = new ArrayList<>();
 
1873                         List<EPApp> app = getApp(uebkey);
 
1874                         final Map<String, Long> params = new HashMap<>();
 
1877                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1878                                 appId = app.get(0).getId();
 
1880                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
 
1881                         Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
 
1884                                 appIdCrt = Restrictions.isNull("appId");
 
1886                                 appIdCrt = Restrictions.eq("appId", appId);
 
1887                         Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
 
1888                         restrictionsList.add(andCrit);
 
1889                         List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
 
1890                         roleList = createCentralRoleObject(app, epRole, roleList, params);
 
1891                         List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
 
1892                         if (globalRoleList.size() > 0)
 
1893                                 roleList.addAll(globalRoleList);
 
1894                 } catch (Exception e) {
 
1895                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
 
1903         @Transactional(rollbackFor = Exception.class)
 
1904         public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
 
1905                 Session localSession = sessionFactory.openSession();
 
1906                 String message = "";
 
1907                 Transaction transaction = null;
 
1908                 boolean response = false;
 
1911                         transaction = localSession.beginTransaction();
 
1912                         List<EPRole> epRoleList = null;
 
1913                         app = getApp(uebkey).get(0);
 
1914                         if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
1915                                 epRoleList = getPortalAppRoleInfo(roleId);
 
1917                                 epRoleList = getPartnerAppRoleInfo(roleId, app);
 
1919                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1920                                 // Delete User Role in External System before deleting role
 
1921                                 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);        
 
1923                         // Delete user app roles
 
1924                         dataAccessService.deleteDomainObjects(EPUserApp.class,
 
1925                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
 
1926                         boolean isPortalRequest = false;
 
1927                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
 
1928                         transaction.commit();
 
1929                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1930                                 // Final call to delete role once all dependencies has been deleted
 
1931                                 deleteRoleInExternalAuthSystem(epRoleList, app);
 
1933                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);            
 
1934                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
 
1936                 } catch(HttpClientErrorException e){
 
1937                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
 
1938                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1939                         message = e.getMessage();
 
1940                 } catch (Exception e) {
 
1941                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
 
1942                         EcompPortalUtils.rollbackTransaction(transaction,
 
1943                                         "deleteDependencyRoleRecord rollback, exception = " + e.toString());
 
1944                         message = e.getMessage();
 
1946                         localSession.close();
 
1948                 return new ExternalRequestFieldsValidator(response,message);
 
1952         @SuppressWarnings("unchecked")
 
1954         public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
 
1957                         // get Permissions from External Auth System
 
1958                         JSONArray extPerms = getExtAuthPermissions(app);
 
1959                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
 
1961                         // get functions in DB
 
1962                         final Map<String, Long> params = new HashMap<>();
 
1963                         final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
 
1964                         params.put(APP_ID, app.getId());
 
1965                         List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
 
1967                         if (!appFunctions.isEmpty()) {
 
1968                                 for (CentralV2RoleFunction roleFunc : appFunctions) {
 
1969                                         roleFuncMap.put(roleFunc.getCode(), roleFunc);
 
1973                         // get Roles for portal in DB
 
1974                         List<EPRole> portalRoleList = getGlobalRolesOfPortal();
 
1975                         final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
 
1976                         for(EPRole epRole : portalRoleList){
 
1977                                 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
 
1981                         final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
 
1983                         // store External Permissions with Pipe and without Pipe (just instance)
 
1984                         final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
 
1985                         final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
 
1986                         for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
 
1987                                 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
 
1988                                 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
 
1989                                 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
 
1992                         // Add if new functions and app role functions were added in
 
1993                         // external auth system
 
1994                         for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
 
1995                                 String code = permsDetail.getInstance();
 
1996                                 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
 
1997                                 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
 
1998                                                 getFunctionCodeKey);
 
1999                                 List<String> roles = permsDetail.getRoles();
 
2000                                 if (roles != null) {
 
2001                                         // Check if function has any roles and which does not exist
 
2002                                         // in External Auth System. If exists delete in local
 
2003                                         addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
 
2007                         // Check if function does exits in External Auth System but exits in
 
2008                         // local then delete function and its dependencies
 
2009                         for (CentralV2RoleFunction roleFunc : appFunctions) {
 
2011                                         ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
 
2012                                                         .get(roleFunc.getCode());
 
2013                                         if (null == getFunctionCodeContainsPipeKey) {
 
2014                                                 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
 
2015                                                 if (null == getFunctionCodeKey) {
 
2016                                                         deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
 
2019                                 } catch (Exception e) {
 
2020                                         logger.error(EELFLoggerDelegate.errorLogger,
 
2021                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
 
2026                         logger.debug(EELFLoggerDelegate.debugLogger,
 
2027                                         "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
 
2028                 } catch (Exception e) {
 
2029                         logger.error(EELFLoggerDelegate.errorLogger,
 
2030                                         "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
 
2035         @SuppressWarnings("unchecked")
 
2036         private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
 
2037                         List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
 
2039                 if (!roleFunctionList.isEmpty()) {
 
2040                         final Map<String, String> appRoleFuncParams = new HashMap<>();
 
2041                         final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
 
2042                         final Map<String, String> currentRolesInExtSystem = new HashMap<>();
 
2043                         appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
 
2044                         appRoleFuncParams.put("appId", String.valueOf(app.getId()));
 
2045                         List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
 
2046                                         appRoleFuncParams, null);
 
2047                         for (LocalRole localRole : localRoleList) {
 
2048                                 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
 
2049                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
 
2051                         for (String addRole : roles) {
 
2052                                 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
 
2054                         for (String extAuthrole : roles) {
 
2055                                 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
 
2056                                 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
 
2057                                 if (isNameSpaceMatching) {
 
2058                                         if (!currentAppRoleFunctionsMap
 
2059                                                         .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
 
2060                                                 EPRole localAddFuntionRole = currentRolesInDB
 
2061                                                                 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
 
2062                                                 if (localAddFuntionRole == null) {
 
2063                                                         checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
 
2065                                                         EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
 
2066                                                         addAppRoleFunc.setAppId(app.getId());
 
2067                                                         addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
 
2068                                                         addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
 
2069                                                         dataAccessService.saveDomainObject(addAppRoleFunc, null);
 
2072                                         // This block is to save global role function if exists
 
2074                                         String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
 
2075                                         boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
 
2076                                         if (checkIfGlobalRoleExists) {
 
2077                                                 final Map<String, Long> params = new HashMap<>();
 
2078                                                 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
 
2079                                                 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
 
2080                                                 params.put("appId", app.getId());
 
2081                                                 params.put("roleId", role.getId());
 
2082                                                 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);                               
 
2083                                                 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
 
2084                                                 if (role != null && !checkIfRoleFunctionExists) {
 
2085                                                         addGlobalRoleFunctions.setAppId(app.getId());
 
2086                                                         addGlobalRoleFunctions.setRoleId(role.getId());
 
2087                                                         if (!app.getId().equals(role.getAppRoleId())) {
 
2088                                                                 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
 
2090                                                                 addGlobalRoleFunctions.setRoleAppId(null);
 
2092                                                         addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
 
2093                                                         dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
 
2098                         for (LocalRole localRoleDelete : localRoleList) {
 
2099                                 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
 
2100                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
 
2101                                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
 
2102                                                         APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
 
2103                                                                         + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
 
2110         private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
 
2111                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2112                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
 
2113                                 roleFunc.getCode());
 
2114                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
 
2115                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
 
2116                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2117                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
 
2118                                 roleFunc.getCode());
 
2120                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2121                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
 
2122                                 roleFunc.getCode());
 
2123                 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
 
2124                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
 
2125                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2126                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
 
2127                                 roleFunc.getCode());
 
2130         private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
 
2131                         List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
 
2132                 if (!currentRolesInDB.containsKey(
 
2133                                 roleList.substring(app.getNameSpace().length() + 1))) {
 
2134                         Role role = addRoleInDBIfDoesNotExists(app,
 
2135                                         roleList.substring(app.getNameSpace().length() + 1));
 
2136                         addIfRoleDescriptionNotExitsInExtSystem(role, app);
 
2137                         if (!roleFunctionList.isEmpty()) {
 
2139                                         if (!roleFunctionList.isEmpty()) {
 
2140                                                 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
 
2141                                                 addAppRoleFunc.setAppId(app.getId());
 
2142                                                 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
 
2143                                                 addAppRoleFunc.setRoleId(role.getId());
 
2144                                                 dataAccessService.saveDomainObject(addAppRoleFunc, null);
 
2146                                 } catch (Exception e) {
 
2147                                         logger.error(EELFLoggerDelegate.errorLogger,
 
2148                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
 
2155         @SuppressWarnings("unchecked")
 
2156         private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
 
2157                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
 
2158                 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
 
2159                                 getFunctionCodeKey);
 
2160                 final Map<String, String> appSyncFuncsParams = new HashMap<>();
 
2161                 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
 
2162                 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
 
2163                 List<CentralV2RoleFunction> roleFunctionList = null;
 
2164                 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
 
2166                 if (roleFunctionList.isEmpty()) {
 
2167                         appSyncFuncsParams.put("functionCd", code);
 
2168                         roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
 
2171                 return roleFunctionList;
 
2174         private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
 
2175                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
 
2177                 String finalFunctionCodeVal = "";       
 
2178                 if (null == getFunctionCodeKey) {
 
2179                         finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
 
2180                         CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
 
2181                         // If function does not exist in local then add!
 
2182                         if (null == checkIfCodeStillExits) {
 
2183                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2184                                                 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
 
2185                                 addFunctionInEcompDB(app, permsDetail, code);
 
2186                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2187                                                 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
 
2190                 return finalFunctionCodeVal;
 
2193         @SuppressWarnings("unchecked")
 
2195         public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
 
2196                 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
 
2197                 List<EPRole> getCurrentRoleList = null;
 
2198                 final Map<String, Long> appParams = new HashMap<>();
 
2199                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2200                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
 
2202                         appParams.put("appId", app.getId());
 
2203                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
 
2205                 for (EPRole role : getCurrentRoleList) {
 
2206                         currentRolesInDB.put(role.getName()
 
2207                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
 
2209                 return currentRolesInDB;
 
2212         private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
 
2214                 ExternalAccessPermsDetail permDetails = null;
 
2215                 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
 
2216                 for (int i = 0; i < extPerms.length(); i++) {
 
2217                         String description = null;
 
2218                         if (extPerms.getJSONObject(i).has("description")) {
 
2219                                 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
 
2221                                 description = extPerms.getJSONObject(i).getString("instance");
 
2223                         if (extPerms.getJSONObject(i).has("roles")) {
 
2224                                 ObjectMapper rolesListMapper = new ObjectMapper();
 
2225                                 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
 
2226                                 List<String> list = rolesListMapper.readValue(resRoles.toString(),
 
2227                                                 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
 
2228                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
 
2229                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
 
2230                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
 
2231                                                                 + extPerms.getJSONObject(i).getString("action"),
 
2232                                                 extPerms.getJSONObject(i).getString("action"), list, description);
 
2233                                 permsDetailList.add(permDetails);
 
2235                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
 
2236                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
 
2237                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
 
2238                                                                 + extPerms.getJSONObject(i).getString("action"),
 
2239                                                 extPerms.getJSONObject(i).getString("action"), description);
 
2240                                 permsDetailList.add(permDetails);
 
2243                 return permsDetailList;
 
2246         private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
 
2247                 ResponseEntity<String> response = null;
 
2248                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2249                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
2250                 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
 
2251                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
2253                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
2254                                                 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
 
2256                 String res = response.getBody();
 
2257                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2258                                 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
 
2259                                 response.getBody());
 
2260                 JSONObject jsonObj = new JSONObject(res);
 
2261                 JSONArray extPerms = jsonObj.getJSONArray("perm");
 
2262                 for (int i = 0; i < extPerms.length(); i++) {
 
2263                         if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
 
2273          * Add function into local DB
 
2276          * @param permsDetail
 
2279         private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
 
2281                 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
 
2282                 addFunction.setAppId(app.getId());
 
2283                 addFunction.setCode(code);
 
2284                 addFunction.setName(permsDetail.getDescription());
 
2285                 dataAccessService.saveDomainObject(addFunction, null);
 
2286                 } catch(Exception e){
 
2287                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
 
2293          * It updates description of a role in external auth system
 
2299         private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
 
2300                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
 
2301                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2303                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
 
2305                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
2306                                         HttpMethod.PUT, entity, String.class);
 
2307                 } catch (HttpClientErrorException e) {
 
2308                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
 
2310                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2311                 } catch (Exception e) {
 
2312                         logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
 
2319          * While sync functions form external auth system if new role found we should add in local and return Role.class object
 
2325         @SuppressWarnings("unchecked")
 
2326         private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
 
2327                 Role setNewRole = new Role();
 
2329                         // functions can have new role created in External Auth System prevent
 
2331                         boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
 
2332                         final Map<String, String> getRoleByNameParams = new HashMap<>();
 
2333                         List<EPRole> getRoleCreated = null;
 
2334                         getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
 
2335                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2336                                 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
 
2337                                 List<EPRole> roleCreated = dataAccessService
 
2338                                                 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
 
2340                                         EPRole epUpdateRole = roleCreated.get(0);
 
2341                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
 
2342                                         dataAccessService.saveDomainObject(epUpdateRole, null);
 
2343                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
 
2344                                                         getRoleByNameParams, null);
 
2346                                         getRoleCreated = roleCreated;
 
2349                                 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
 
2352                         if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
 
2353                                 EPRole roleObject = getRoleCreated.get(0);
 
2354                                 setNewRole.setId(roleObject.getId());
 
2355                                 setNewRole.setName(roleObject.getName());
 
2356                                 setNewRole.setActive(roleObject.getActive());
 
2357                                 setNewRole.setPriority(roleObject.getPriority());
 
2359                 } catch (Exception e) {
 
2360                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
 
2365         @SuppressWarnings("unchecked")
 
2366         private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
 
2367                 boolean isCreated = false;
 
2368                 final Map<String, String> roleParams = new HashMap<>();
 
2369                 roleParams.put(APP_ROLE_NAME_PARAM, role);
 
2370                 List<EPRole> roleCreated = null;
 
2371                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2372                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
 
2375                         roleParams.put("appId", String.valueOf(app.getId()));
 
2376                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
 
2379                 if (roleCreated == null || roleCreated.isEmpty()) {
 
2380                         roleParams.put("appId", String.valueOf(app.getId()));
 
2381                         EPRole epRoleNew = new EPRole();
 
2382                         epRoleNew.setActive(true);
 
2383                         epRoleNew.setName(role);
 
2384                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2385                                 epRoleNew.setAppId(null);
 
2387                                 epRoleNew.setAppId(app.getId());
 
2389                         dataAccessService.saveDomainObject(epRoleNew, null);
 
2398         @SuppressWarnings("unchecked")
 
2399         public Integer bulkUploadFunctions(String uebkey) throws Exception {
 
2400                 EPApp app = getApp(uebkey).get(0);
 
2401                 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
 
2402                 CentralV2RoleFunction cenRoleFunc = null;
 
2403                 Integer functionsAdded = 0;
 
2405                         for (RoleFunction roleFunc : roleFuncList) {
 
2406                                 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
 
2407                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
 
2410                 } catch(HttpClientErrorException e){
 
2411                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
 
2412                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2413                 } catch (Exception e) {
 
2414                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
 
2416                 return functionsAdded;
 
2420         public Integer bulkUploadRoles(String uebkey) throws Exception {
 
2421                 List<EPApp> app = getApp(uebkey);
 
2422                 List<EPRole> roles = getAppRoles(app.get(0).getId());
 
2423                 List<CentralV2Role> cenRoleList = new ArrayList<>();
 
2424                 final Map<String, Long> params = new HashMap<>();
 
2425                 Integer rolesListAdded = 0;
 
2427                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
 
2428                         ObjectMapper mapper = new ObjectMapper();
 
2429                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
 
2430                         String roleList = mapper.writeValueAsString(cenRoleList);
 
2431                         List<Role> roleObjectList = mapper.readValue(roleList,
 
2432                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
 
2433                         for (Role role : roleObjectList) {
 
2434                                 addRoleInExternalSystem(role, app.get(0));
 
2437                 } catch (Exception e) {
 
2438                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
 
2441                 return rolesListAdded;
 
2445          * It creating new role in external auth system while doing bulk upload
 
2451         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
 
2452                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
 
2453                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2455                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
 
2457                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
2458                                         HttpMethod.POST, entity, String.class);
 
2459                 } catch(HttpClientErrorException e){
 
2460                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
 
2461                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2462                 } catch (Exception e) {
 
2463                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
2464                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
 
2466                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
 
2472         @SuppressWarnings("unchecked")
 
2473         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
 
2474                 EPApp app = getApp(uebkey).get(0);
 
2475                 List<EPRole> roles = getAppRoles(app.getId());
 
2476                 final Map<String, Long> params = new HashMap<>();
 
2477                 Integer roleFunctions = 0;
 
2479                         for (EPRole role : roles) {
 
2480                                 params.put("roleId", role.getId());
 
2481                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
 
2483                                 if (!appRoleFunc.isEmpty()) {
 
2484                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
 
2485                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
 
2490                 } catch(HttpClientErrorException e){
 
2491                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
 
2492                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2493                 } catch (Exception e) {
 
2494                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
 
2496                 return roleFunctions;
 
2500          * Its adding a role function while doing bulk upload
 
2502          * @param addRoleFunc
 
2506         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
 
2507                 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
 
2508                 ExternalAccessRolePerms extRolePerms = null;
 
2509                 ExternalAccessPerms extPerms = null;
 
2510                 ObjectMapper mapper = new ObjectMapper();
 
2512                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2514                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
 
2515                                         addRoleFunc.getFunctionName());
 
2516                         extRolePerms = new ExternalAccessRolePerms(extPerms,
 
2517                                         app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
2518                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
2519                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
2521                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
 
2522                                         HttpMethod.POST, entity, String.class);
 
2523                 } catch (Exception e) {
 
2524                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
2525                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2526                                                 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
 
2528                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
 
2535         public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
 
2536                 EPApp app = getApp(uebkey).get(0);
 
2537                 CentralV2RoleFunction cenRoleFunc = null;
 
2538                 for (RoleFunction roleFunction : roleFunctionsList) {
 
2539                         cenRoleFunc = new CentralV2RoleFunction(roleFunction.getCode(), roleFunction.getName());
 
2540                         addRoleFunctionInExternalSystem(cenRoleFunc, app);
 
2545         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
 
2546                 EPApp app = getApp(uebkey).get(0);
 
2547                 for (Role role : roleList) {
 
2548                         addRoleInExternalSystem(role, app);
 
2552         @SuppressWarnings("unchecked")
 
2554         public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
 
2555                 EPApp app = getApp(uebkey).get(0);
 
2556                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2557                 for (Role role : roleList) {
 
2559                                 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
 
2560                                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
 
2561                                 ObjectMapper roleFunctionsMapper = new ObjectMapper();
 
2562                                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
 
2563                                 while (itetaror.hasNext()) {
 
2564                                         Object nextValue = itetaror.next();
 
2565                                         RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
 
2566                                         roleFunctionListNew.add(roleFunction);
 
2568                                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
 
2569                                                 .collect(Collectors.toList());
 
2570                                 for (RoleFunction roleFunction : listWithoutDuplicates) {
 
2571                                         String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
 
2572                                         ExternalAccessRolePerms extRolePerms = null;
 
2573                                         ExternalAccessPerms extPerms = null;
 
2574                                         ObjectMapper mapper = new ObjectMapper();
 
2575                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
 
2577                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
 
2578                                                         app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
2579                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
2580                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
2581                                         template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
2582                                                         + "role/perm", HttpMethod.PUT, entity, String.class);
 
2584                         } catch (Exception e) {
 
2585                                 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
2586                                         logger.error(EELFLoggerDelegate.errorLogger,
 
2587                                                         "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
 
2589                                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
 
2599         public void syncApplicationRolesWithEcompDB(EPApp app) {
 
2601                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
 
2602                         //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
 
2603                         syncRoleFunctionFromExternalAccessSystem(app);
 
2604                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");     
 
2606                         ObjectMapper mapper = new ObjectMapper();
 
2607                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
 
2608                         // Get Permissions from External Auth System
 
2609                         JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
 
2611                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
 
2612                         List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
 
2615                         List<EPRole> finalRoleList = new ArrayList<>();
 
2616                         for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
 
2617                                 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
 
2618                                 finalRoleList.add(ecompRole);
 
2621                         List<EPRole> applicationRolesList;
 
2622                         applicationRolesList = getAppRoles(app.getId());
 
2623                         List<String> applicationRoleIdList = new ArrayList<>();
 
2624                         for (EPRole applicationRole : applicationRolesList) {
 
2625                                 applicationRoleIdList.add(applicationRole.getName());
 
2628                         List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
 
2629                         for (EPRole aafRole : finalRoleList) {
 
2630                                 if (!applicationRoleIdList.contains(aafRole.getName())) {
 
2631                                         roleListToBeAddInEcompDB.add(aafRole);
 
2635                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
 
2636                         // Check if roles exits in external Access system and if not make inactive in DB
 
2637                         inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
 
2639                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
 
2640                         // It checks properties in the external auth system app role description and updates role in local
 
2641                         checkAndUpdateRoleInDB(app, finalRoleList);
 
2643                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
 
2644                         // Add new roles in DB and updates role description in External Auth System 
 
2645                         addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
 
2646                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
 
2647                 } catch (HttpClientErrorException e) {
 
2648                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
 
2649                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2650                 } catch (Exception e) {
 
2651                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
 
2657          * It adds new roles in DB and updates description in External Auth System
 
2660          * @param roleListToBeAddInEcompDB
 
2662         @SuppressWarnings("unchecked")
 
2663         private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
 
2664                 EPRole roleToBeAddedInEcompDB;
 
2665                 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
 
2667                                 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
 
2668                                 if (app.getId() == 1) {
 
2669                                         roleToBeAddedInEcompDB.setAppRoleId(null);
 
2671                                 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
 
2672                                 List<EPRole> getRoleCreatedInSync = null;
 
2673                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2674                                         final Map<String, String> globalRoleParams = new HashMap<>();
 
2675                                         globalRoleParams.put("appId", String.valueOf(app.getId()));
 
2676                                         globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
 
2677                                         getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
 
2678                                         EPRole epUpdateRole = getRoleCreatedInSync.get(0);
 
2679                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
 
2680                                         dataAccessService.saveDomainObject(epUpdateRole, null);
 
2682                                 List<EPRole> roleList = new ArrayList<>();
 
2683                                 final Map<String, String> params = new HashMap<>();
 
2685                                 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
 
2686                                 boolean isPortalRole = false;
 
2687                                 if (app.getId() == 1) {
 
2688                                         isPortalRole = true;
 
2689                                         roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
 
2691                                         isPortalRole = false;
 
2692                                         params.put(APP_ID, app.getId().toString());
 
2693                                         roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
 
2695                                 EPRole role = roleList.get(0);
 
2696                                 Role aaFrole = new Role();
 
2697                                 aaFrole.setId(role.getId());
 
2698                                 aaFrole.setActive(role.getActive());
 
2699                                 aaFrole.setPriority(role.getPriority());
 
2700                                 aaFrole.setName(role.getName());
 
2701                                 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
 
2702                         } catch (Exception e) {
 
2703                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2704                                                 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
 
2711          * It checks description in External Auth System if found any changes updates in DB
 
2714          * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
 
2716         @SuppressWarnings("unchecked")
 
2717         private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
 
2718                 for (EPRole roleItem : finalRoleList) {
 
2719                         final Map<String, String> roleParams = new HashMap<>();
 
2720                         List<EPRole> currentList = null;
 
2721                         roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
 
2722                         if (app.getId() == 1) {
 
2723                                 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
 
2725                                 roleParams.put(APP_ID, app.getId().toString());
 
2726                                 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
 
2729                         if (!currentList.isEmpty()) {
 
2731                                         Boolean aafRoleActive;
 
2732                                         Boolean localRoleActive;
 
2734                                         aafRoleActive = Boolean.valueOf(roleItem.getActive());
 
2735                                         localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
 
2736                                         result = aafRoleActive.equals(localRoleActive);
 
2737                                         EPRole updateRole = currentList.get(0);
 
2740                                                 updateRole.setActive(roleItem.getActive());
 
2741                                                 dataAccessService.saveDomainObject(updateRole, null);
 
2743                                         if (roleItem.getPriority() != null
 
2744                                                         && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
 
2745                                                 updateRole.setPriority(roleItem.getPriority());
 
2746                                                 dataAccessService.saveDomainObject(updateRole, null);
 
2748                                 } catch (Exception e) {
 
2749                                         logger.error(EELFLoggerDelegate.errorLogger,
 
2750                                                         "syncApplicationRolesWithEcompDB: Failed to update role ", e);
 
2757          * It de-activates application roles in DB if not present in External Auth system  
 
2760          * @param finalRoleList contains list of current roles present in External Auth System
 
2761          * @param applicationRolesList contains list of current roles present in DB
 
2763         @SuppressWarnings("unchecked")
 
2764         private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
 
2765                         List<EPRole> applicationRolesList) {
 
2766                 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
 
2767                 for (EPRole extrole : finalRoleList) {
 
2768                         checkRolesInactive.put(extrole.getName(), extrole);
 
2770                 for (EPRole role : applicationRolesList) {
 
2772                                 final Map<String, String> extRoleParams = new HashMap<>();
 
2773                                 List<EPRole> roleList = null;
 
2774                                 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
 
2775                                 if (!checkRolesInactive.containsKey(role.getName())) {
 
2776                                         if (app.getId() == 1) {
 
2777                                                 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
 
2779                                                 extRoleParams.put(APP_ID, app.getId().toString());
 
2780                                                 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
 
2782                                         if(!roleList.isEmpty()) {
 
2783                                                 EPRole updateRoleInactive = roleList.get(0);
 
2784                                                 updateRoleInactive.setActive(false);
 
2785                                                 dataAccessService.saveDomainObject(updateRoleInactive, null);
 
2788                         } catch (Exception e) {
 
2789                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2790                                                 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
 
2796         @SuppressWarnings("unchecked")
 
2797         public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
 
2798                         ObjectMapper mapper, JSONArray extRole)
 
2799                         throws IOException {
 
2800                 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
 
2801                 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
 
2802                 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); 
 
2803                 List<String> functionCodelist = new ArrayList<>();
 
2804                 for (int i = 0; i < extRole.length(); i++) {
 
2805                         ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
 
2806                         EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
 
2807                         JSONObject Role = (JSONObject) extRole.get(i);
 
2808                         if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
 
2809                                 ApplicationRole.setActive("true");
 
2810                                 ApplicationRole.setAppId(IS_NULL_STRING);
 
2811                                 ApplicationRole.setPriority(IS_NULL_STRING);
 
2812                                 ApplicationRole.setAppRoleId(IS_NULL_STRING);
 
2813                                 String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
 
2814                                 ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
 
2816                                 String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
 
2817                                 ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
 
2820                         SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
 
2821                         if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
 
2822                                 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
 
2823                                 for (int j = 0; j < extPerm.length(); j++) {
 
2824                                         JSONObject perms = extPerm.getJSONObject(j);
 
2825                                         boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"), app.getNameSpace());
 
2826                                         if (isNamespaceMatching) {
 
2827                                                 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
 
2828                                                                 perms.getString("instance"), perms.getString("action"));
 
2829                                                 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
 
2830                                                 functionCodelist.add(ePAppRoleFunction.getCode());
 
2831                                                 externalAccessPermsOfRole.add(externalAccessPerms);
 
2837                         if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
 
2838                                 externalRoleDetail.setActive(false);
 
2840                                 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
 
2842                         externalRoleDetail.setName(ApplicationRole.getName());
 
2844                         if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
 
2845                                 externalRoleDetail.setAppId(null);
 
2846                         } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
 
2847                                 externalRoleDetail.setAppId(app.getId());
 
2849                                 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
 
2852                         if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
 
2853                                 externalRoleDetail.setPriority(null);
 
2855                                 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
 
2858                         if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
 
2859                                 externalRoleDetail.setAppRoleId(null);
 
2862                         // get role functions from DB
 
2863                         final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
 
2864                         if (!ApplicationRole.getId().equals(IS_NULL_STRING)) {
 
2865                                 final Map<String, Long> appRoleFuncsParams = new  HashMap<>();
 
2866                                 appRoleFuncsParams.put("appId", app.getId());
 
2867                                 appRoleFuncsParams.put("roleId", Long.valueOf(ApplicationRole.getId()));
 
2868                                 List<EPAppRoleFunction> appRoleFunctions = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
 
2869                                 if (!appRoleFunctions.isEmpty()) {
 
2870                                         for (EPAppRoleFunction roleFunc : appRoleFunctions) {
 
2871                                                 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
 
2876                         if (!externalAccessPermsOfRole.isEmpty()) {
 
2877                                 // Adding functions to role
 
2878                                 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
 
2879                                         EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
 
2880                                         if (checkRoleFunctionExits == null) {
 
2881                                                 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
 
2882                                                                 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
 
2883                                                                 + externalpermission.getAction();
 
2884                                                 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
 
2885                                                 if (checkRoleFunctionPipeExits == null) {
 
2887                                                                 final Map<String, String> appFuncsParams = new  HashMap<>();
 
2888                                                                 appFuncsParams.put("appId", String.valueOf(app.getId()));
 
2889                                                                 appFuncsParams.put("functionCd", externalpermission.getInstance());
 
2890                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2891                                                                                 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
 
2892                                                                                 externalpermission.getInstance());
 
2893                                                                 List<CentralV2RoleFunction> roleFunction = null;
 
2894                                                                 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
 
2895                                                                 if (roleFunction.isEmpty()) {
 
2896                                                                         appFuncsParams.put("functionCd", funcCode);
 
2897                                                                         roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
 
2899                                                                 if (!roleFunction.isEmpty()) {
 
2900                                                                         EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
 
2901                                                                         apRoleFunction.setAppId(app.getId());
 
2902                                                                         apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
 
2903                                                                         apRoleFunction.setCode(roleFunction.get(0).getCode());
 
2904                                                                         dataAccessService.saveDomainObject(apRoleFunction, null);
 
2906                                                         } catch (Exception e) {
 
2907                                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2908                                                                                 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
 
2914                         externalRoleDetailsList.add(externalRoleDetail);
 
2916                 return externalRoleDetailsList;
 
2920         public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
 
2921                 ResponseEntity<String> response = null;
 
2922                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2923                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
2924                 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
 
2925                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
2927                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
2928                                                 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
 
2929                 String res = response.getBody();
 
2930                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2931                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
 
2933                 JSONObject jsonObj = new JSONObject(res);
 
2934                 JSONArray extRole = jsonObj.getJSONArray("role");
 
2935                 for (int i = 0; i < extRole.length(); i++) {
 
2936                         if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
 
2937                                         || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
 
2938                                         || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
 
2939                                                         && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
 
2948         public JSONArray getAllUsersByRole(String roleName) throws Exception{
 
2949                 ResponseEntity<String> response = null;
 
2950                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2951                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
2952                 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
 
2953                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
2955                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
2956                                                 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
 
2957                 String res = response.getBody();
 
2958                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2959                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
 
2961                 JSONObject jsonObj = new JSONObject(res);
 
2962                 JSONArray extRole = jsonObj.getJSONArray("userRole");
 
2969          * It converts from ExternalRoleDetails.class object to EPRole.class object
 
2971          * @param externalRoleDetails
 
2972          * @return EPRole object
 
2974         private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
 
2975                 EPRole role = new EPRole();
 
2976                 role.setActive(externalRoleDetails.isActive());
 
2977                 role.setAppId(externalRoleDetails.getAppId());
 
2978                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
 
2979                 role.setName(externalRoleDetails.getName());
 
2980                 role.setPriority(externalRoleDetails.getPriority());
 
2984         @SuppressWarnings("unchecked")
 
2986         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
 
2987                 EPApp app = getApp(uebkey).get(0);
 
2988                 final Map<String, String> params = new HashMap<>();
 
2989                 params.put("uebKey", app.getUebKey());
 
2990                 List<BulkUploadUserRoles> userRolesList = null;
 
2991                 Integer userRolesAdded = 0;
 
2992                 if (app.getCentralAuth()) {
 
2993                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
 
2994                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
 
2995                                 if(!userRolesUpload.getOrgUserId().equals("su1234")){
 
2996                                         addUserRoleInExternalSystem(userRolesUpload);
 
3001                 return userRolesAdded;
 
3005          * Its adding a user role in external auth system while doing bulk upload 
 
3007          * @param userRolesUpload
 
3009         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
 
3012                         ObjectMapper mapper = new ObjectMapper();
 
3013                         if (EPCommonSystemProperties
 
3014                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
 
3015                                 name = userRolesUpload.getOrgUserId()
 
3016                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
 
3018                         ExternalAccessUser extUser = new ExternalAccessUser(name,
 
3019                                         userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
3020                         String userRole = mapper.writeValueAsString(extUser);
 
3021                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
3022                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
 
3024                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
 
3025                                         HttpMethod.POST, entity, String.class);
 
3026                 } catch(HttpClientErrorException e){
 
3027                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
 
3028                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
3029                 } catch (Exception e) {
 
3030                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
3031                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
 
3033                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
 
3039         public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
 
3044                         //It should delete only when it portal's roleId
 
3045                         if(appId.equals(PortalConstants.PORTAL_APP_ID)){
 
3046                         // Delete from fn_role_function
 
3047                         sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
 
3048                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3049                         query = localSession.createSQLQuery(sql);
 
3050                         query.executeUpdate();
 
3052                         // Delete from fn_role_composite
 
3053                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
 
3054                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3055                         query = localSession.createSQLQuery(sql);
 
3056                         query.executeUpdate();
 
3059                         // Delete from ep_app_role_function
 
3060                         sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
 
3061                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3062                         query = localSession.createSQLQuery(sql);
 
3063                         query.executeUpdate();
 
3065                         // Delete from ep_role_notification
 
3066                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
 
3067                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3068                         query = localSession.createSQLQuery(sql);
 
3069                         query.executeUpdate();
 
3071                         // Delete from fn_user_pseudo_role
 
3072                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
 
3073                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3074                         query = localSession.createSQLQuery(sql);
 
3075                         query.executeUpdate();
 
3077                         // Delete form EP_WIDGET_CATALOG_ROLE
 
3078                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
 
3079                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3080                         query = localSession.createSQLQuery(sql);
 
3081                         query.executeUpdate();
 
3083                         // Delete form EP_WIDGET_CATALOG_ROLE
 
3084                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
 
3085                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3086                         query = localSession.createSQLQuery(sql);
 
3087                         query.executeUpdate();
 
3089                         if(!isPortalRequest) {
 
3090                                 // Delete form fn_menu_functional_roles
 
3091                                 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
 
3092                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3093                                 query = localSession.createSQLQuery(sql);
 
3094                                 query.executeUpdate();  
 
3096                 } catch (Exception e) {
 
3097                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
 
3098                         throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
 
3103         @SuppressWarnings("unchecked")
 
3105         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
 
3106                 List<String> appMenuFunctionsList = null;
 
3108                         EPApp app = getApp(uebkey).get(0);
 
3109                         final Map<String, Long> appParams = new HashMap<>();
 
3110                         appParams.put(APP_ID, app.getId());
 
3111                         appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
 
3112                 } catch (Exception e) {
 
3113                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
 
3114                         return appMenuFunctionsList;
 
3116                 return appMenuFunctionsList;
 
3119         @SuppressWarnings({ "unchecked"})
 
3121         public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
 
3122                 List<String> usersList = new ArrayList<>();
 
3123                 List<EcompUser> usersfinalList = new ArrayList<>();
 
3125                         EPApp app = getApp(uebkey).get(0);
 
3126                         final Map<String, Long> appParams = new HashMap<>();
 
3127                         appParams.put("appId", app.getId());
 
3128                         List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
 
3129                                         .executeNamedQuery("ApplicationUserRoles", appParams, null);
 
3130                         for (EcompUserRoles ecompUserRole : userList) {
 
3131                                 boolean found = false;
 
3132                                 Set<EcompRole> roles = null;
 
3133                                 for (EcompUser user : usersfinalList) {
 
3134                                         if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
 
3135                                                 EcompRole ecompRole = new EcompRole();
 
3136                                                 ecompRole.setId(ecompUserRole.getRoleId());
 
3137                                                 ecompRole.setName(ecompUserRole.getRoleName());
 
3138                                                 roles = user.getRoles();
 
3139                                                 roles.add(ecompRole);
 
3140                                                 user.setRoles(roles);
 
3147                                         EcompUser epUser = new EcompUser();
 
3148                                         epUser.setOrgId(ecompUserRole.getOrgId());
 
3149                                         epUser.setManagerId(ecompUserRole.getManagerId());
 
3150                                         epUser.setFirstName(ecompUserRole.getFirstName());
 
3151                                         epUser.setLastName(ecompUserRole.getLastName());
 
3152                                         epUser.setPhone(ecompUserRole.getPhone());
 
3153                                         epUser.setEmail(ecompUserRole.getEmail());
 
3154                                         epUser.setOrgUserId(ecompUserRole.getOrgUserId());
 
3155                                         epUser.setOrgCode(ecompUserRole.getOrgCode());
 
3156                                         epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
 
3157                                         epUser.setJobTitle(ecompUserRole.getJobTitle());
 
3158                                         epUser.setLoginId(ecompUserRole.getLoginId());
 
3159                                         epUser.setActive(true);
 
3160                                         roles = new HashSet<>();
 
3161                                         EcompRole ecompRole = new EcompRole();
 
3162                                         ecompRole.setId(ecompUserRole.getRoleId());
 
3163                                         ecompRole.setName(ecompUserRole.getRoleName());
 
3164                                         roles.add(ecompRole);
 
3165                                         epUser.setRoles(roles);
 
3166                                         usersfinalList.add(epUser);
 
3169                         ObjectMapper mapper = new ObjectMapper();
 
3171                         for (EcompUser u1 : usersfinalList) {
 
3172                                 String str = mapper.writeValueAsString(u1);
 
3175                 } catch (Exception e) {
 
3176                         logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
 
3179                 return usersfinalList;
 
3184         public Role ConvertCentralRoleToRole(String result) {
 
3185                 ObjectMapper mapper = new ObjectMapper();
 
3186                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
3187                 Role newRole = new Role();
 
3189                         newRole = mapper.readValue(result, Role.class);
 
3190                 } catch (IOException e) {
 
3191                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
 
3193                 if (newRole.getRoleFunctions() != null) {
 
3194                         @SuppressWarnings("unchecked")
 
3195                         Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
 
3196                         Set<RoleFunction> roleFunctionListNew = new HashSet<>();
 
3197                         Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
 
3198                         while (itetaror.hasNext()) {
 
3199                                 Object nextValue = itetaror.next();
 
3200                                 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
 
3201                                 roleFunctionListNew.add(roleFun);
 
3203                         newRole.setRoleFunctions(roleFunctionListNew);
 
3209         @SuppressWarnings("unchecked")
 
3210         public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
 
3211                 Map<String, String> params = new HashMap<>();
 
3212                 params.put("userId", userId);
 
3213                 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
 
3215                         centralizedAppsList =  dataAccessService
 
3216                                         .executeNamedQuery("getCentralizedAppsOfUser", params, null);
 
3217                 }catch (Exception e) {
 
3218                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
 
3220                 return centralizedAppsList;
 
3223         @SuppressWarnings("unchecked")
 
3224         public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
 
3225                 Map<String, Long> params = new HashMap<>();
 
3226                 params.put("appId", appId);
 
3227                 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
 
3229                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
 
3231                 } catch (Exception e) {
 
3232                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
 
3234                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
 
3235                 if (globalRoles.size() > 0)
 
3236                         rolesfinalList = finalListOfCentralRoles(globalRoles);
 
3237                 return rolesfinalList;
 
3240         @SuppressWarnings("unchecked")
 
3241         private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
 
3242                 CentralV2Role finalGlobalrole = null;
 
3243                 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
 
3244                 Map<String, Long> params = new HashMap<>();
 
3245                 params.put("roleId", roleId);
 
3246                 params.put("requestedAppId", requestedAppId);
 
3248                         roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
 
3250                 } catch (Exception e) {
 
3251                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
 
3253                 if (roleWithApplicationRoleFucntions.size() > 0) {
 
3254                         List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
 
3255                         finalGlobalrole = rolesfinalList.get(0);
 
3257                         List<EPRole> roleList = getPortalAppRoleInfo(roleId);
 
3258                         finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
 
3260                 return finalGlobalrole;
 
3263         private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
 
3264                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
 
3265                 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
 
3266                         boolean found = false;
 
3267                         for (CentralV2Role cenRole : rolesfinalList) {
 
3268                                 if (role.getRoleId().equals(cenRole.getId())) {
 
3269                                         SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
 
3270                                         CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
 
3271                                         roleFunctions.add(cenRoleFun);
 
3272                                         cenRole.setRoleFunctions(roleFunctions);
 
3278                                 CentralV2Role cenrole = new CentralV2Role();
 
3279                                 cenrole.setName(role.getRoleName());
 
3280                                 cenrole.setId(role.getRoleId());
 
3281                                 cenrole.setActive(role.isActive());
 
3282                                 cenrole.setPriority(role.getPriority());
 
3283                                 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
 
3284                                 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
 
3285                                 roleFunctions.add(cenRoleFun);
 
3286                                 cenrole.setRoleFunctions(roleFunctions);
 
3287                                 rolesfinalList.add(cenrole);
 
3290                 return rolesfinalList;
 
3293         private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
 
3297                 CentralV2RoleFunction cenRoleFun;
 
3298                 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
 
3299                         instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
 
3300                         type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
 
3301                         action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
 
3302                         cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
 
3304                         type = getFunctionType(role.getFunctionCd());
 
3305                         action = getFunctionAction(role.getFunctionCd());
 
3306                         cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
 
3311         @SuppressWarnings("unchecked")
 
3313         public List<EPRole> getGlobalRolesOfPortal() {
 
3314                 List<EPRole> globalRoles = new ArrayList<>();
 
3316                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
 
3317                 } catch (Exception e) {
 
3318                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
 
3323         private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
 
3324          return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
 
3325                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
 
3326                                 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
 
3331         public List<RoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
 
3332                 List<RoleFunction> addRoleFuncList = new ArrayList<>();
 
3333                 for(CentralV2RoleFunction cenRoleFunc : answer){
 
3334                         RoleFunction setRoleFunc = new RoleFunction();
 
3335                         setRoleFunc.setCode(cenRoleFunc.getCode());
 
3336                         setRoleFunc.setName(cenRoleFunc.getName());
 
3337                         addRoleFuncList.add(setRoleFunc);
 
3339                 return addRoleFuncList;
 
3343         public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
 
3344                 CentralUser sendUserRoles = null;
 
3347                         CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
 
3348                         sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
 
3349                 } catch (Exception e) {
 
3350                         logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
 
3352                 return sendUserRoles;
 
3357          * It returns V2 CentralUser object if user has any roles and permissions
 
3361          * @return CentralUser object
 
3364         private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
 
3366                 List<EPUser> epUserList;
 
3367                 List<EPApp> appList = getApp(uebkey);
 
3368                 app = appList.get(0);
 
3369                 epUserList = getUser(loginId);
 
3370                 EPUser user = epUserList.get(0);
 
3371                 Set<EPUserApp> userAppSet = user.getEPUserApps();
 
3372                 return createEPUser(user, userAppSet, app);
 
3376          * It converts V2 CentralUser object to old version CentralUser object
 
3379          * @return EPUser object
 
3381         private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
 
3382                         Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
 
3383                         Set<CentralUserApp> userApps = new TreeSet<>();
 
3384                         for(CentralV2UserApp userApp : userV2Apps){                             
 
3385                                 CentralApp app  = userApp.getApp();
 
3386                                 CentralUserApp cua = new CentralUserApp();
 
3387                                 cua.setUserId(null);
 
3389                                 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
 
3390                                 for(CentralV2RoleFunction  cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){                                      
 
3391                                         CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());                                                            
 
3392                                         cenRoleFunction.add(cenRoleFunc);
 
3394                                 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().isActive(), userApp.getRole().getPriority(),
 
3399                         return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(), 
 
3400                                         cenV2User.getCreatedId(),cenV2User.getModifiedId(), 
 
3401                                         cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(), 
 
3402                                         cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), 
 
3403                                         cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
 
3404                                         cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(), 
 
3405                                         cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(), 
 
3406                                         cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(), 
 
3407                                         cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(), 
 
3408                                         cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(), 
 
3409                                         cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(), 
 
3410                                         cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
 
3411                                         cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(), 
 
3412                                         cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
 
3413                                         cenV2User.isOnline(),cenV2User.getChatId(), 
 
3418         public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
 
3419                 List<CentralRole> cenRoleList = new ArrayList<>();
 
3420                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
 
3421                         for(CentralV2Role v2CenRole : v2CenRoleList){
 
3422                                 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
 
3423                                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
 
3424                                         cenRoleFuncList.add(roleFunc);
 
3426                                 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), cenRoleFuncList);
 
3427                                 cenRoleList.add(role);
 
3433         public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
 
3434                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
3435                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
3436                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
 
3437                 ResponseEntity<String> response = null;
 
3440                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
3441                                                         + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
 
3442                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
 
3443                                         response.getStatusCode().value());
 
3444                 } catch (HttpClientErrorException e) {
 
3445                         logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
 
3446                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
3447                         if (e.getStatusCode() == HttpStatus.NOT_FOUND)
 
3448                                 throw new InvalidApplicationException("Invalid NameSpace");
 
3456         public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
 
3457                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
 
3458                 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
 
3459                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
 
3460                         cenRoleFuncList.add(roleFunc);
 
3462                 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(),
 
3466         @SuppressWarnings("unchecked")
 
3468         public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
 
3469                 EPApp app = getApp(uebkey).get(0);
 
3470                 final Map<String, String> params = new HashMap<>();
 
3471                 params.put("uebKey", app.getUebKey());
 
3472                 params.put("roleId", String.valueOf(roleId));
 
3473                 List<BulkUploadUserRoles> userRolesList = null;
 
3474                 Integer userRolesAdded = 0;
 
3475                 if (app.getCentralAuth()) {
 
3476                         userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
 
3477                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
 
3478                                 userRolesUpload.setRoleName(modifiedRoleName);
 
3479                                 if(!userRolesUpload.getOrgUserId().equals("su1234")){
 
3480                                         addUserRoleInExternalSystem(userRolesUpload);
 
3485                 return userRolesAdded;
 
3489         public String encodeFunctionCode(String funCode){
 
3490                 String encodedString = funCode;
 
3491                 List<Pattern> encodingList = new ArrayList<>();
 
3492                 encodingList.add(Pattern.compile("/"));
 
3493                 encodingList.add(Pattern.compile("-"));
 
3494                 for (Pattern xssInputPattern : encodingList) {
 
3495                         encodedString = xssInputPattern.matcher(encodedString)
 
3496                                         .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
 
3498                 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
 
3499                 return encodedString;