2  * ============LICENSE_START==========================================
 
   4  * ===================================================================
 
   5  * Copyright (C) 2017-2018 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============================================
 
  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.List;
 
  48 import java.util.SortedSet;
 
  49 import java.util.TreeSet;
 
  50 import java.util.regex.Pattern;
 
  51 import java.util.stream.Collectors;
 
  53 import org.apache.commons.codec.DecoderException;
 
  54 import org.apache.commons.codec.binary.Hex;
 
  55 import org.hibernate.Query;
 
  56 import org.hibernate.Session;
 
  57 import org.hibernate.SessionFactory;
 
  58 import org.hibernate.Transaction;
 
  59 import org.hibernate.criterion.Criterion;
 
  60 import org.hibernate.criterion.Restrictions;
 
  61 import org.json.JSONArray;
 
  62 import org.json.JSONObject;
 
  63 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
 
  64 import org.onap.portalapp.portal.domain.CentralizedApp;
 
  65 import org.onap.portalapp.portal.domain.EPApp;
 
  66 import org.onap.portalapp.portal.domain.EPAppRoleFunction;
 
  67 import org.onap.portalapp.portal.domain.EPRole;
 
  68 import org.onap.portalapp.portal.domain.EPUser;
 
  69 import org.onap.portalapp.portal.domain.EPUserApp;
 
  70 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
 
  71 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
 
  72 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
 
  73 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
 
  74 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
 
  75 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
 
  76 import org.onap.portalapp.portal.exceptions.InvalidUserException;
 
  77 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
 
  78 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
 
  79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
 
  80 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
 
  81 import org.onap.portalapp.portal.transport.BulkUploadRoleFunction;
 
  82 import org.onap.portalapp.portal.transport.BulkUploadUserRoles;
 
  83 import org.onap.portalapp.portal.transport.CentralApp;
 
  84 import org.onap.portalapp.portal.transport.CentralRole;
 
  85 import org.onap.portalapp.portal.transport.CentralRoleFunction;
 
  86 import org.onap.portalapp.portal.transport.CentralUser;
 
  87 import org.onap.portalapp.portal.transport.CentralUserApp;
 
  88 import org.onap.portalapp.portal.transport.CentralV2Role;
 
  89 import org.onap.portalapp.portal.transport.CentralV2User;
 
  90 import org.onap.portalapp.portal.transport.CentralV2UserApp;
 
  91 import org.onap.portalapp.portal.transport.CentralizedAppRoles;
 
  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.ExternalAccessUserRoleDetail;
 
  99 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
 
 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.EcompRoleFunction;
 
 111 import org.onap.portalsdk.core.restful.domain.EcompUser;
 
 112 import org.onap.portalsdk.core.service.DataAccessService;
 
 113 import org.onap.portalsdk.core.util.SystemProperties;
 
 114 import org.springframework.beans.factory.annotation.Autowired;
 
 115 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
 116 import org.springframework.http.HttpEntity;
 
 117 import org.springframework.http.HttpHeaders;
 
 118 import org.springframework.http.HttpMethod;
 
 119 import org.springframework.http.HttpStatus;
 
 120 import org.springframework.http.ResponseEntity;
 
 121 import org.springframework.stereotype.Service;
 
 122 import org.springframework.transaction.annotation.Transactional;
 
 123 import org.springframework.web.client.HttpClientErrorException;
 
 124 import org.springframework.web.client.RestTemplate;
 
 126 import com.fasterxml.jackson.core.JsonProcessingException;
 
 127 import com.fasterxml.jackson.databind.DeserializationFeature;
 
 128 import com.fasterxml.jackson.databind.ObjectMapper;
 
 129 import com.fasterxml.jackson.databind.type.TypeFactory;
 
 131 @Service("externalAccessRolesService")
 
 132 @EnableAspectJAutoProxy
 
 135 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
 
 137         private static final String APP_ROLE_NAME_PARAM = "appRoleName";
 
 139         private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
 
 141         private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
 
 143         private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
 
 145         private static final String FUNCTION_CODE_PARAMS = "functionCode";
 
 147         private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
 
 149         private static final String OWNER = ".owner";
 
 151         private static final String ADMIN = ".admin";
 
 153         private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
 
 155         private static final String FUNCTION_PIPE = "|";
 
 157         private static final String EXTERNAL_AUTH_PERMS = "perms";
 
 159         private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
 
 161         private static final String IS_EMPTY_JSON_STRING = "{}";
 
 163         private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
 
 165         private static final String APP_ID = "appId";
 
 167         private static final String ROLE_NAME = "name";
 
 169         private static final String APP_ID_EQUALS = " app_id = ";
 
 171         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
 
 174         private DataAccessService dataAccessService;
 
 177         private EPAppService epAppService;
 
 180         private SessionFactory sessionFactory;
 
 183         EPRoleService ePRoleService;
 
 185         RestTemplate template = new RestTemplate();
 
 188         // These decode values are based on HexDecoder
 
 189         static final String decodeValueOfForwardSlash = "2f";
 
 190         static final String decodeValueOfHiphen = "2d";
 
 191         static final String decodeValueOfStar = "2a";
 
 193         @SuppressWarnings("unchecked")
 
 194         public List<EPRole> getAppRoles(Long appId) throws Exception {
 
 195                 List<EPRole> applicationRoles = null;
 
 196                 final Map<String, Long> appParams = new HashMap<>();
 
 199                                 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
 
 201                                 appParams.put("appId", appId);
 
 202                                 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
 
 204                 } catch (Exception e) {
 
 205                         logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
 
 208                 return applicationRoles;
 
 211         @SuppressWarnings("unchecked")
 
 213         public List<EPApp> getApp(String uebkey) throws Exception {
 
 214                 List<EPApp> app = null;
 
 216                         final Map<String, String> appUebkeyParams = new HashMap<>();
 
 217                         appUebkeyParams.put("appKey", uebkey);
 
 218                         app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
 
 219                         if(!app.isEmpty() && !app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 220                                 throw new InactiveApplicationException("Application:"+app.get(0).getName()+" is Unavailable");
 
 222                 } catch (Exception e) {
 
 223                         logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
 
 230          * It returns  single application role from external auth system 
 
 233          * @return JSON string which contains application role details
 
 236         private String getSingleAppRole(String addRole, EPApp app) throws Exception {
 
 237                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 238                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
 239                 ResponseEntity<String> response = null;
 
 240                 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
 
 241                 response = template.exchange(
 
 242                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
 
 245                                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
 
 246                                 HttpMethod.GET, entity, String.class);
 
 247                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 248                                 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
 
 249                                 response.getStatusCode().value());
 
 250                 return response.getBody();
 
 254         public boolean addRole(Role addRole, String uebkey) throws Exception {
 
 255                 boolean response = false;
 
 256                 ResponseEntity<String> addResponse = null;
 
 257                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 258                 EPApp app = getApp(uebkey).get(0);
 
 259                 String newRole = updateExistingRoleInExternalSystem(addRole, app);
 
 260                 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
 
 261                 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
 
 262                 addResponse = template.exchange(
 
 263                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
 264                                 HttpMethod.POST, entity, String.class);
 
 265                 if (addResponse.getStatusCode().value() == 201) {
 
 267                         logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system  and response code: {} ", addResponse.getStatusCode().value());
 
 269                 if (addResponse.getStatusCode().value() == 406) {
 
 270                         logger.error(EELFLoggerDelegate.errorLogger,
 
 271                                         "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
 
 278          * It deletes record in external auth system
 
 281          * @return JSON String which has status code and response body 
 
 284         private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
 
 285                 ResponseEntity<String> delResponse = null;
 
 286                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 287                 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
 
 288                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
 
 289                 delResponse = template.exchange(
 
 290                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
 
 291                                 HttpMethod.DELETE, entity, String.class);
 
 292                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", delRole, delResponse.getStatusCode().value());
 
 297          * It updates role in external auth system
 
 299          * @param updateExtRole
 
 301          * @return true if success else false
 
 303          *                                      If updateRoleInExternalSystem fails we catch it in logger for detail message
 
 305         private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
 
 306                 boolean response = false;
 
 307                 ObjectMapper mapper = new ObjectMapper();
 
 308                 ResponseEntity<String> deleteResponse = null;
 
 309                 List<EPRole> epRoleList = null;
 
 310                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
 
 311                                 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
 
 312                         epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
 
 314                         epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
 
 316                 // Assigning functions to global role
 
 317                 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
 
 318                         List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
 
 319                         EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
 
 320                         addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
 
 323                         String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
 
 324                         List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
 
 325                         if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
 
 326                                 JSONObject jsonObj = new JSONObject(appRole);
 
 327                                 JSONArray extRole = jsonObj.getJSONArray("role");
 
 328                                 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
 
 329                                         String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
 
 330                                         Map<String, String> delRoleKeyMapper = new HashMap<>();
 
 331                                         delRoleKeyMapper.put(ROLE_NAME, roleName);
 
 332                                         String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
 
 333                                         deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
 
 334                                         if (deleteResponse.getStatusCode().value() != 200) {
 
 335                                                 throw new ExternalAuthSystemException(deleteResponse.getBody());
 
 337                                         addRole(updateExtRole, app.getUebKey());
 
 339                                         String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
 
 340                                         String name = extRole.getJSONObject(0).getString(ROLE_NAME);
 
 341                                         List<ExternalAccessPerms> list = new ArrayList<>();
 
 342                                         if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
 
 343                                                 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
 
 344                                                 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
 
 345                                                                 .constructCollectionType(List.class, ExternalAccessPerms.class));
 
 347                                         // If role name or role functions are updated then delete
 
 348                                         // record in External System and add new record to avoid
 
 350                                         boolean isRoleNameChanged = false;
 
 351                                         if (!desc.equals(updateExtRole.getName())) {
 
 352                                                 isRoleNameChanged = true;
 
 353                                                 deleteRoleInExtSystem(mapper, name);
 
 354                                                 addRole(updateExtRole, app.getUebKey());
 
 355                                                 // add partner functions to the global role in External Auth System
 
 356                                                 if (!list.isEmpty() && isGlobalRole) {
 
 357                                                         addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
 
 360                                                                 perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
 
 361                                                 // if role name is changes please ignore the previous functions in External Auth
 
 362                                                 // and update with user requested functions
 
 363                                                 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
 
 365                                         // Delete role in External System if role is inactive
 
 366                                         if (!updateExtRole.getActive()) {
 
 367                                                 deleteRoleInExtSystem(mapper, name);
 
 369                                         if (!isRoleNameChanged) {
 
 370                                                 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
 
 375                                 // It seems like role exists in local DB but not in External
 
 377                                 if (updateExtRole.getActive()) {
 
 378                                         addRole(updateExtRole, app.getUebKey());
 
 379                                         ExternalAccessRolePerms extAddRolePerms = null;
 
 380                                         ExternalAccessPerms extAddPerms = null;
 
 381                                         List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
 
 382                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 383                                         for (RoleFunction roleFunc : roleFunctionListAdd) {
 
 384                                                 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(),
 
 385                                                                 roleFunc.getCode(), roleFunc.getAction());
 
 386                                                 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
 
 387                                                                 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
 
 388                                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 389                                                 response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
 
 397         private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
 
 398                         throws JsonProcessingException, Exception, ExternalAuthSystemException {
 
 399                 ResponseEntity<String> deleteResponse;
 
 400                 Map<String, String> delRoleKeyMapper = new HashMap<>();
 
 401                 delRoleKeyMapper.put(ROLE_NAME, name);
 
 402                 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
 
 403                 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
 
 404                 if (deleteResponse.getStatusCode().value() != 200) {
 
 405                         logger.error(EELFLoggerDelegate.errorLogger,
 
 406                                         "updateRoleInExternalSystem:  Failed to delete role in external system due to {} ",
 
 407                                         deleteResponse.getBody());
 
 408                         throw new ExternalAuthSystemException(deleteResponse.getBody());
 
 412         private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
 
 413                         List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
 
 415                 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
 
 416                 for (RoleFunction addPerm : roleFunctionListNew) {
 
 417                         updateRoleFunc.put(addPerm.getCode(), addPerm);
 
 419                 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
 
 420                 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
 
 421                 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
 
 422                 // Update permissions in the ExternalAccess System
 
 423                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 424                 if (!list.isEmpty()) {
 
 425                         for (ExternalAccessPerms perm : list) {
 
 426                                 RoleFunction roleFunc =  updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());   
 
 427                                 if (roleFunc==null) {
 
 428                                         RoleFunction roleFuncPipeFilter =  updateRoleFunc.get(perm.getInstance());
 
 429                                         if(roleFuncPipeFilter == null)
 
 430                                         removePermForRole(perm, mapper, name, headers);
 
 432                                 extRolePermMap.put(perm.getInstance(), perm);
 
 433                                 extRolePermMapPipes.put(
 
 434                                                 perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
 
 438                 if (!roleFunctionListNew.isEmpty()) {
 
 439                         for (RoleFunction roleFunc : roleFunctionListNew) {
 
 440                                 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
 
 441                                         ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
 
 443                                                 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
 
 447                                         if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
 
 448                                                 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
 
 458          * Adds function to the role in the external auth system while editing a role or updating new functions to a role 
 
 461         private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
 
 462                         HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
 
 464                 ExternalAccessRolePerms extRolePerms;
 
 465                 ExternalAccessPerms extPerms;
 
 469                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
 
 470                         code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
 471                         type = getFunctionCodeType(roleFunc.getCode());
 
 472                         action = getFunctionCodeAction(roleFunc.getCode());
 
 474                         code = roleFunc.getCode();
 
 475                         type = roleFunc.getCode().contains("menu") ? "menu" : "url";
 
 478                 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
 
 479                 extRolePerms = new ExternalAccessRolePerms(extPerms,
 
 480                                 app.getNameSpace() + "."
 
 481                                                 + updateExtRole.getName().replaceAll(
 
 482                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
 
 484                 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
 485                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
 486                 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
 
 487                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
 
 488                 ResponseEntity<String> addResponse = template.exchange(
 
 489                                 SystemProperties.getProperty(
 
 490                                                 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
 
 491                                 HttpMethod.POST, entity, String.class);
 
 492                 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value()!= 409) {
 
 494                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 495                                         "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
 
 496                                         addResponse.getStatusCode().getReasonPhrase(),
 
 497                                         addResponse.getStatusCode().value());
 
 500                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 501                                         "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
 
 502                                         updateRolePerms, addResponse.getStatusCode().value());
 
 507         private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
 
 508                         EPApp app, Role updateExtRole) throws Exception {
 
 509                 for (ExternalAccessPerms perm : permslist) {
 
 510                         if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
 
 511                                 ExternalAccessRolePerms extAddGlobalRolePerms = null;
 
 512                                 ExternalAccessPerms extAddPerms = null;
 
 513                                 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
 
 514                                 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
 
 515                                                 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
 
 516                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 517                                 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
 
 518                                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 519                                 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
 
 520                                 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
 
 521                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
 523                                         ResponseEntity<String> addResponse = template
 
 524                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 525                                                                         + "role/perm", HttpMethod.POST, entity, String.class);
 
 526                                         if (addResponse.getStatusCode().value() != 201) {
 
 527                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 528                                                                 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
 
 529                                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
 
 531                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 532                                                                 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
 
 533                                                                 addResponse.getStatusCode().value());
 
 535                                 } catch (Exception e) {
 
 536                                         logger.error(EELFLoggerDelegate.errorLogger, "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ",
 
 543         @SuppressWarnings("unchecked")
 
 544         private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
 
 547                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
 
 548                         //GET Permissions from External Auth System
 
 549                         JSONArray extPerms = getExtAuthPermissions(app);
 
 550                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
 
 551                         final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
 
 552                         final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
 
 553                         final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
 
 554                         final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
 
 555                         for (ExternalAccessPermsDetail permDetail : permsDetailList) {
 
 556                                 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
 
 557                                 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
 
 560                         // Add If function does not exists for role in External Auth System
 
 561                         for (RoleFunction roleFunc : roleFunctionListNew) {
 
 562                                 String roleFuncCode = "";
 
 563                                 ExternalAccessPermsDetail permsDetail;
 
 564                                 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
 
 565                                         roleFuncCode = roleFunc.getCode();
 
 566                                         permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
 
 568                                         roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
 569                                         permsDetail = existingPermsWithRoles.get(roleFuncCode);
 
 571                                 if (null == permsDetail.getRoles() || !permsDetail.getRoles()
 
 572                                                 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE + epRoleList.get(0).getName().replaceAll(
 
 573                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
 
 574                                         addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
 
 576                                 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
 
 577                                 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
 
 579                         // Delete functions if exists in External Auth System but not in incoming request
 
 580                         final Map<String, Long> epAppRoleFuncParams =  new HashMap<>();
 
 581                         epAppRoleFuncParams.put("requestedAppId", app.getId());
 
 582                         epAppRoleFuncParams.put("roleId",updateExtRole.getId());
 
 583                         List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
 
 584                         for(GlobalRoleWithApplicationRoleFunction globalRoleFunc: globalRoleFunctionList){
 
 585                                 String globalRoleFuncWithoutPipes = "";
 
 586                                 RoleFunction roleFunc = null;
 
 587                                 if(globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
 
 588                                         globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
 
 589                                         roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
 
 591                                         globalRoleFuncWithoutPipes  = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
 
 592                                         roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
 
 594                                 if(roleFunc == null){
 
 595                                         ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
 
 596                                         ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), permDetailFromMap.getAction());
 
 597                                         String roleName = portalAppInfo.getNameSpace()+"."+globalRoleFunc.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
 
 598                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 599                                         removePermForRole(perm, mapper, roleName, headers);
 
 602                         logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
 
 603                 } catch (Exception e) {
 
 604                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed",e);
 
 609         private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, ObjectMapper mapper, EPApp app,
 
 610                         EPApp portalAppInfo) throws Exception {
 
 612                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
 
 613                         ExternalAccessRolePerms extAddRolePerms = null;
 
 614                         ExternalAccessPerms extAddPerms = null;
 
 615                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 619                                 if (addFunction.getCode().contains(FUNCTION_PIPE)) {
 
 620                                         code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
 
 621                                         type = getFunctionCodeType(addFunction.getCode());
 
 622                                         action = getFunctionCodeAction(addFunction.getCode());
 
 624                                         code = addFunction.getCode();
 
 625                                         type = addFunction.getCode().contains("menu") ? "menu" : "url";
 
 628                                 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
 
 629                                 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
 
 630                                                 portalAppInfo.getNameSpace() + "." + globalRole.getName().replaceAll(
 
 631                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 632                                 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
 
 633                                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
 634                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
 
 635                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
 636                                 ResponseEntity<String> addResponse = template
 
 637                                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 638                                                                 + "role/perm", HttpMethod.POST, entity, String.class);
 
 639                                 if (addResponse.getStatusCode().value() != 201) {
 
 640                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 641                                                         "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
 
 642                                                         addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
 
 644                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 645                                                         "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
 
 646                                                         addResponse.getStatusCode().value());
 
 648                         logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
 
 650                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed",e);
 
 655         private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
 
 656                         HttpHeaders headers) throws JsonProcessingException {
 
 658                 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
 
 659                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
 660                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
 
 661                 ResponseEntity<String> addResponse = template.exchange(
 
 662                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
 
 663                                 HttpMethod.POST, entity, String.class);
 
 664                 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
 
 666                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 667                                         "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
 
 668                                         addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
 
 671                         logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value());
 
 678          * It converts list of functions in updateExtRole parameter to the RoleFunction object
 
 680          * @param updateExtRole
 
 681          * @return list of functions 
 
 683         @SuppressWarnings("unchecked")
 
 684         private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
 
 685                 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
 
 686                 List<RoleFunction> roleFunctionList = new ArrayList<>();
 
 687                 ObjectMapper roleFuncMapper = new ObjectMapper();
 
 688                 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
 
 689                 while (itetaror.hasNext()) {
 
 690                         Object nextValue = itetaror.next();
 
 691                         RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
 
 692                         roleFunctionList.add(roleFunction);
 
 694                 return roleFunctionList.stream().distinct().collect(Collectors.toList());
 
 698          * It delete permissions/functions in the external auth system
 
 704          * @throws JsonProcessingException 
 
 707         private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
 
 708                         throws ExternalAuthSystemException, JsonProcessingException {
 
 709                 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
 
 710                 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
 
 712                 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
 
 713                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
 
 714                 ResponseEntity<String> deletePermResponse = template
 
 715                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
 
 716                                                 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
 
 717                 if (deletePermResponse.getStatusCode().value() != 200) {
 
 718                         throw new ExternalAuthSystemException(deletePermResponse.getBody());
 
 720                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
 
 721                                 permDetails, deletePermResponse.getStatusCode().value());
 
 722                 } catch(Exception e){
 
 723                         if(e.getMessage().contains("404")){
 
 724                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", permDetails, e.getMessage());                               
 
 732          * It will create new role in the External Auth System
 
 736          * @return true if successfully added in the system else false
 
 738          *             If fails to add role in the system
 
 740         private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception, HttpClientErrorException {
 
 742                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 743                 ObjectMapper mapper = new ObjectMapper();
 
 744                 String addNewRole = "";
 
 745                 ExternalAccessRole extRole = new ExternalAccessRole();
 
 746                 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 747                 extRole.setDescription(String.valueOf(newRole.get(0).getName()));
 
 748                 addNewRole = mapper.writeValueAsString(extRole);
 
 749                 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
 
 750                 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
 
 751                 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
 
 752                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
 753                                 HttpMethod.POST, postEntity, String.class);
 
 754                         if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
 
 755                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 756                                                 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
 
 757                                                 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
 
 759                 }catch(HttpClientErrorException ht){
 
 760                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ newRole.get(0).getId(), null);
 
 761                         logger.error(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}",
 
 763                         throw new HttpClientErrorException(ht.getStatusCode());
 
 769          * It updates existing role in the External Auth System
 
 772          *            It Contains role information
 
 774          * @return string which is formatted to match with the external auth system
 
 775          * @throws JsonProcessingException
 
 777         private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
 
 778                 ObjectMapper mapper = new ObjectMapper();
 
 779                 String addNewRole = "";
 
 780                 ExternalAccessRole extRole = new ExternalAccessRole();
 
 781                 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
 782                 extRole.setDescription(String.valueOf(addRole.getName()));
 
 783                 addNewRole = mapper.writeValueAsString(extRole);
 
 788          * It create a role in the external auth system and then in our local 
 
 792          * @return true else false
 
 795         @SuppressWarnings("unchecked")
 
 796         @Transactional(rollbackFor = Exception.class)
 
 797         public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {         
 
 798                 boolean result = false;
 
 799                 EPRole epRole = null;
 
 800                 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
 
 801                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
 
 802                 ObjectMapper mapper = new ObjectMapper();
 
 803                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
 
 804                 while (itetaror.hasNext()) {
 
 805                         Object nextValue = itetaror.next();
 
 806                         RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
 
 807                         roleFunctionListNew.add(roleFunction);
 
 809                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
 
 811                         if (addRoleInDB.getId() == null) { // check if it is new role
 
 812                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
 813                                         checkIfRoleExitsInExternalSystem(addRoleInDB, app);
 
 815                                 EPRole epRoleNew = new EPRole();
 
 816                                 epRoleNew.setActive(addRoleInDB.getActive());
 
 817                                 epRoleNew.setName(addRoleInDB.getName());
 
 818                                 epRoleNew.setPriority(addRoleInDB.getPriority());
 
 819                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 820                                         epRoleNew.setAppId(null);
 
 822                                         epRoleNew.setAppId(app.getId());
 
 824                                 dataAccessService.saveDomainObject(epRoleNew, null);
 
 825                                 List<EPRole> getRoleCreated = null;
 
 826                                 final Map<String, String> epAppRoleParams =  new HashMap<>();
 
 827                                 final Map<String, String> epAppPortalRoleParams =  new HashMap<>();
 
 828                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 829                                         epAppRoleParams.put("appId", String.valueOf(app.getId()));
 
 830                                         epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
 
 831                                         List<EPRole> roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
 
 832                                         EPRole epUpdateRole = roleCreated.get(0);
 
 833                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
 
 834                                         dataAccessService.saveDomainObject(epUpdateRole, null);
 
 835                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
 
 837                                         epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
 
 838                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null);
 
 840                                 // Add role in External Auth system
 
 841                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
 842                                         addNewRoleInExternalSystem(getRoleCreated, app);
 
 845                         } else { // if role already exists then update it
 
 846                                 EPRole globalRole = null;
 
 847                                 List<EPRole> applicationRoles;
 
 848                                 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
 
 849                                 boolean isGlobalRole = false;
 
 850                                 if (!globalRoleList.isEmpty()) {
 
 851                                         EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
 
 858                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
 
 859                                                 || (globalRole != null && app.getId() != globalRole.getAppId())) {
 
 860                                         applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
 
 862                                         applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
 
 864                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
 865                                         updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
 
 866                                         // Add all user to the re-named role in external auth system
 
 867                                         if (!applicationRoles.isEmpty()
 
 868                                                         && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
 
 869                                                 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
 
 870                                                                 addRoleInDB.getName());
 
 873                                 deleteRoleFunction(app, applicationRoles);
 
 874                                 if (!applicationRoles.isEmpty()) {
 
 875                                         epRole = applicationRoles.get(0);
 
 876                                         epRole.setName(addRoleInDB.getName());
 
 877                                         epRole.setPriority(addRoleInDB.getPriority());
 
 878                                         epRole.setActive(addRoleInDB.getActive());
 
 879                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 880                                                 epRole.setAppId(null);
 
 881                                                 epRole.setAppRoleId(null);
 
 882                                         } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
 
 883                                                         && applicationRoles.get(0).getAppRoleId() == null) {
 
 884                                                 epRole.setAppRoleId(epRole.getId());
 
 886                                         dataAccessService.saveDomainObject(epRole, null);
 
 888                                 Long roleAppId = null;
 
 889                                 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
 
 890                                         roleAppId = PortalConstants.PORTAL_APP_ID;
 
 891                                 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
 
 894                 } catch (Exception e) {
 
 895                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
 
 903          * It validates whether role exists in external auth system
 
 910         private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
 
 911                 getNameSpaceIfExists(app);
 
 912                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 913                 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
 
 914                 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
 
 915                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
 916                 ResponseEntity<String> checkRoleInExternalSystem = template
 
 917                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
 
 918                                                 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
 
 919                 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
 
 920                         logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
 
 921                         throw new ExternalAuthSystemException(" Role already exists in external system");
 
 926          * It saves list of functions to the role in portal
 
 928          * @param roleFunctionListNew
 
 930          * @param applicationRoles
 
 933         @SuppressWarnings("unchecked")
 
 934         private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
 
 936                 final Map<String, String> getAppFunctionParams = new HashMap<>(); 
 
 938                 for (RoleFunction roleFunc : roleFunctionListNew) {
 
 939                         String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
 940                         EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
 
 941                         appRoleFunc.setAppId(app.getId());
 
 942                         appRoleFunc.setRoleId(applicationRoles.get(0).getId());
 
 943                         appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
 
 944                         getAppFunctionParams.put("appId", String.valueOf(app.getId()));
 
 945                         getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
 
 946                         // query to check if function code has pipes
 
 947                         List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
 
 948                         if(roleFunction.isEmpty()){
 
 949                                 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
 
 950                                 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
 
 952                         if(roleFunction.size() > 1){
 
 953                                 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
 
 954                                 appRoleFunc.setCode(getExactFunctionCode.getCode());
 
 956                                 appRoleFunc.setCode(roleFunction.get(0).getCode());
 
 959                         dataAccessService.saveDomainObject(appRoleFunc, null);
 
 965          * It filters the app functions which starts with similar name in the result set
 
 968          * @param roleFunction
 
 969          * @return CentralRoleFunction 
 
 971         private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
 
 972                 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>(); 
 
 973                 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>(); 
 
 974                 CentralV2RoleFunction getExactFunctionCode = null;
 
 975                 for(CentralV2RoleFunction cenRoleFunction : roleFunction){
 
 976                         appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
 
 977                         appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
 
 979                 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
 
 980                 if(getExactFunctionCode == null){
 
 981                         getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
 
 983                 return getExactFunctionCode;
 
 987          * It deletes all EPAppRoleFunction records in the portal
 
 992         @SuppressWarnings("unchecked")
 
 993         private void deleteRoleFunction(EPApp app, List<EPRole> role) {
 
 994                 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
 
 995                 appRoleFuncsParams.put("appId", app.getId());
 
 996                 appRoleFuncsParams.put("roleId", role.get(0).getId());
 
 997                 List<EPAppRoleFunction> appRoleFunctionList =  dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
 
 998                 if (!appRoleFunctionList.isEmpty()) {
 
 999                         for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
 
1000                                 dataAccessService.deleteDomainObject(approleFunction, null);
 
1006         @SuppressWarnings("unchecked")
 
1007         public List<EPUser> getUser(String loginId) throws InvalidUserException{
 
1008                 final Map<String, String> userParams = new HashMap<>();
 
1009                 userParams.put("org_user_id", loginId);
 
1010                 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
 
1011                 if (userList.isEmpty()) {
 
1012                         throw new InvalidUserException("User not found");
 
1018         public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
 
1019                 final Map<String, String> params = new HashMap<>();
 
1020                 List<EPUser> userList = null;
 
1021                 CentralV2User cenV2User = null;
 
1022                 String result = null;
 
1024                         params.put("orgUserIdValue", loginId);
 
1025                         List<EPApp> appList = getApp(uebkey);
 
1026                         if (!appList.isEmpty()) {
 
1027                                 userList = getUser(loginId);
 
1028                                 if (!userList.isEmpty()) {
 
1029                                         ObjectMapper mapper = new ObjectMapper();
 
1030                                         cenV2User = getV2UserAppRoles(loginId, uebkey);
 
1031                                         result = mapper.writeValueAsString(cenV2User);
 
1032                                 } else if (userList.isEmpty()) {
 
1033                                         throw new InvalidUserException("User not found");
 
1036                                 throw new InactiveApplicationException("Application not found");
 
1038                 } catch (Exception e) {
 
1039                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
 
1046         public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
 
1047                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
 
1048                 List<CentralV2Role> roleList = new ArrayList<>();
 
1049                 final Map<String, Long> params = new HashMap<>();
 
1051                         List<EPApp> app = getApp(uebkey);
 
1052                         List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
 
1053                         roleList = createCentralRoleObject(app, appRolesList, roleList, params);
 
1054                         if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
 
1055                             List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
 
1056                                 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
 
1057                             List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
 
1058                                 if (!globalRolesList.isEmpty()) {
 
1059                                         for (EPRole eprole : globalRolesList) {
 
1060                                                 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
 
1061                                                 portalsGlobalRolesFinlaList.add(cenRole);
 
1063                                         roleList.addAll(globalRoleList);
 
1064                                         for (CentralV2Role role : portalsGlobalRolesFinlaList) {
 
1065                                                 CentralV2Role result = roleList.stream()
 
1066                                                                         .filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
 
1071                                         for (EPRole role : globalRolesList) {
 
1072                                                 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
 
1073                                                 roleList.add(cenRole);
 
1077                 } catch (Exception e) {
 
1078                         logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
 
1081                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
 
1082                 return roleList.stream().distinct().collect(Collectors.toList());
 
1085         @SuppressWarnings("unchecked")
 
1087         public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
 
1088                 EPApp app = getApp(uebkey).get(0);
 
1089                 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
 
1090                 final Map<String, Long> params = new HashMap<>();
 
1091                 params.put(APP_ID, app.getId());
 
1092                 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
 
1093                 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
 
1094                         String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
 
1095                         String type = getFunctionCodeType(roleFuncItem.getCode());
 
1096                         String action = getFunctionCodeAction(roleFuncItem.getCode());
 
1097                         roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
 
1098                         roleFuncItem.setType(type);
 
1099                         roleFuncItem.setAction(action);
 
1100                         finalRoleList.add(roleFuncItem);
 
1102                 return finalRoleList;
 
1107         public String getFunctionCodeAction(String roleFuncItem) {
 
1108                 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
 
1109                                 : EcompPortalUtils.getFunctionAction(roleFuncItem);
 
1113         public String getFunctionCodeType(String roleFuncItem) {
 
1115                 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
 
1116                                 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
 
1118                 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
 
1119                                 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
 
1120                                 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
 
1122                 } else if (roleFuncItem.contains(FUNCTION_PIPE)
 
1123                                 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
 
1124                         type = EcompPortalUtils.getFunctionType(roleFuncItem);
 
1131          * It check whether function code has no pipes and no url string in it
 
1133          * @param roleFuncItem
 
1134          * @return true or false
 
1136         private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
 
1137                 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
 
1142          * It check whether function code has pipes and url string in it  
 
1144          * @param roleFuncItem
 
1145          * @return true or false
 
1147         private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
 
1148                 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
 
1153          * It check whether function code has no pipes and has url string in it 
 
1155          * @param roleFuncItem
 
1156          * @return true or false
 
1158         private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
 
1159                 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
 
1163          * It returns user detail information which is deep copy of EPUser.class object
 
1171         @SuppressWarnings("unchecked")
 
1172         private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
 
1173                 final Map<String, Long> params = new HashMap<>();
 
1174                 CentralV2User userAppList = new CentralV2User();
 
1175                 CentralV2User user1 = null;
 
1176                 final Map<String, Long> params1 = new HashMap<>();
 
1177                 List<EPRole> globalRoleList = new ArrayList<>();
 
1179                         if (app.getId() != PortalConstants.PORTAL_APP_ID) {
 
1180                                 params1.put("userId", userInfo.getId());
 
1181                                 params1.put("appId", app.getId());
 
1182                                 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
 
1184                         userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
 
1185                         for (EPUserApp userApp : userAppSet) {
 
1186                                 if (userApp.getRole().getActive()) {
 
1187                                         EPApp epApp = userApp.getApp();
 
1188                                         String globalRole = userApp.getRole().getName().toLowerCase();
 
1189                                         if (((epApp.getId().equals(app.getId()))
 
1190                                                         && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
 
1191                                                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
 
1192                                                                         && (globalRole.toLowerCase().startsWith("global_")))) {
 
1193                                                 CentralV2UserApp cua = new CentralV2UserApp();
 
1194                                                 cua.setUserId(null);
 
1195                                                 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
 
1196                                                                 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
 
1197                                                                 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
 
1198                                                                 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
 
1199                                                                 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
 
1200                                                                 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
 
1201                                                                 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
 
1202                                                                 epApp.getUebTopicName());
 
1205                                                 if (globalRole.toLowerCase().startsWith("global_")
 
1206                                                                 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
 
1207                                                                 && !epApp.getId().equals(app.getId())) {
 
1208                                                         appId = app.getId();
 
1209                                                         EPRole result = null;
 
1210                                                         if (globalRoleList.size() > 0)
 
1211                                                                 result = globalRoleList.stream()
 
1212                                                                                 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
 
1217                                                         appId = userApp.getApp().getId();
 
1219                                                 params.put("roleId", userApp.getRole().getId());
 
1220                                                 params.put(APP_ID, appId);
 
1221                                                 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
 
1222                                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
 
1223                                                 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
 
1224                                                 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
 
1225                                                         String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
1226                                                         String type = getFunctionCodeType(roleFunc.getCode());
 
1227                                                         String action = getFunctionCodeAction(roleFunc.getCode());
 
1228                                                         CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
 
1229                                                                         functionCode, roleFunc.getName(), null, type, action, null);
 
1230                                                         roleFunctionSet.add(cenRoleFunc);
 
1232                                                 Long userRoleId = null;
 
1233                                                 if (globalRole.toLowerCase().startsWith("global_")
 
1234                                                                 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1235                                                         userRoleId = userApp.getRole().getId();
 
1237                                                         userRoleId = userApp.getRole().getAppRoleId();
 
1239                                                 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
 
1240                                                                 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
 
1241                                                                 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
 
1242                                                                 userApp.getRole().getName(), userApp.getRole().getActive(),
 
1243                                                                 userApp.getRole().getPriority(), roleFunctionSet, null, null);
 
1244                                                 cua.setRole(cenRole);
 
1246                                                 userAppList.getUserApps().add(cua);
 
1251                         user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
 
1252                                         userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
 
1253                                         userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
 
1254                                         userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
 
1255                                         userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
 
1256                                         userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
 
1257                                         userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
 
1258                                         userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
 
1259                                         userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
 
1260                                         userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
 
1261                                         userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
 
1262                                         userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
 
1263                                         userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
 
1264                                         userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
 
1265                                         userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
 
1266                 } catch (Exception e) {
 
1267                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
 
1274         public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
 
1275                 final Map<String, Long> params = new HashMap<>();
 
1276                 List<CentralV2Role> roleList = new ArrayList<>();
 
1277                 CentralV2Role cenRole = new CentralV2Role();
 
1278                 List<EPRole> roleInfo = null;
 
1279                 List<EPApp> app = null;
 
1281                         app = getApp(uebkey);
 
1282                         if (app.isEmpty()) {
 
1283                                 throw new InactiveApplicationException("Application not found");
 
1285                         if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
 
1286                                 List<EPRole> globalRoleList = new ArrayList<>();
 
1287                                 globalRoleList = getGlobalRolesOfPortal();
 
1288                                 if (globalRoleList.size() > 0) {
 
1289                                         EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
 
1292                                                 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
 
1295                         if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1296                                 roleInfo = getPortalAppRoleInfo(roleId);
 
1298                                 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
 
1300                         roleList = createCentralRoleObject(app, roleInfo, roleList, params);
 
1301                         if (roleList.isEmpty()) {
 
1305                 } catch (Exception e) {
 
1306                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
 
1310                 return roleList.get(0);
 
1313         @SuppressWarnings("unchecked")
 
1314         private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
 
1315                 List<EPRole> roleInfo;
 
1316                 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
 
1317                 getPartnerAppRoleParams.put("appRoleId", roleId);
 
1318                 getPartnerAppRoleParams.put("appId", app.getId());                              
 
1319                 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
 
1320                 if(roleInfo.isEmpty()) {
 
1321                         getPartnerAppRoleParams.put("appRoleId", roleId);
 
1322                         roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
 
1327         @SuppressWarnings("unchecked")
 
1328         private List<EPRole> getPortalAppRoleInfo(Long roleId) {
 
1329                 List<EPRole> roleInfo;
 
1330                 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
 
1331                 getPortalAppRoleParams.put("roleId", roleId);
 
1332                 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
 
1338          * It returns list of app roles along with role functions and which went through deep copy
 
1345          * @throws DecoderException 
 
1347         @SuppressWarnings("unchecked")
 
1348         private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
 
1349                         List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
 
1350                 for (EPRole role : roleInfo) {
 
1351                         params.put("roleId", role.getId());
 
1352                         params.put(APP_ID, app.get(0).getId());
 
1353                         List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
 
1355                         SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
 
1356                         for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
 
1357                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
1358                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
 
1359                                 String type = getFunctionCodeType(roleFunc.getCode());
 
1360                                 String action = getFunctionCodeAction(roleFunc.getCode());
 
1361                                 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
 
1362                                                 roleFunc.getName(), null, type, action, null);
 
1363                                 roleFunctionSet.add(cenRoleFunc);
 
1365                         SortedSet<CentralV2Role> childRoles = new TreeSet<>();
 
1366                         SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
 
1367                         CentralV2Role cenRole = null;
 
1368                         if (role.getAppRoleId() == null) {
 
1369                                 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
 
1370                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
 
1371                                                 roleFunctionSet, childRoles, parentRoles);
 
1373                                 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
 
1374                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
 
1375                                                 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
 
1377                         roleList.add(cenRole);
 
1382         @SuppressWarnings("unchecked")
 
1384         public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
 
1385                 String code = EcompPortalUtils.getFunctionCode(functionCode);
 
1386                 String encodedCode = encodeFunctionCode(code);
 
1387                 CentralV2RoleFunction roleFunc = null;
 
1388                 EPApp app = getApp(uebkey).get(0);
 
1389                 List<CentralV2RoleFunction> getRoleFuncList = null;
 
1390                 final Map<String, String> params = new HashMap<>();
 
1392                         params.put(FUNCTION_CODE_PARAMS, functionCode);
 
1393                         params.put(APP_ID, String.valueOf(app.getId()));
 
1394                         getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
 
1395                         if (getRoleFuncList.isEmpty()) {
 
1396                                 params.put(FUNCTION_CODE_PARAMS, encodedCode);
 
1397                                 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
 
1398                                 if (getRoleFuncList.isEmpty()) {
 
1402                         if (getRoleFuncList.size() > 1) {
 
1403                                 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
 
1404                                 if (cenV2RoleFunction == null)
 
1406                                 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
 
1408                                 // Check even if single record have pipes
 
1409                                 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
 
1410                                         roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
 
1412                                         roleFunc = getRoleFuncList.get(0);
 
1415                 } catch (Exception e) {
 
1416                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
 
1422         private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
 
1423                 CentralV2RoleFunction roleFunc;
 
1424                 String functionCodeFormat = getRoleFuncList.getCode();
 
1425                 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
 
1426                         String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
 
1427                         String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
 
1428                         String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
 
1429                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
 
1430                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
 
1431                                         getRoleFuncList.getEditUrl());
 
1433                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
 
1434                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(),
 
1435                                         getRoleFuncList.getEditUrl());
 
1441         public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
 
1442                 boolean saveOrUpdateFunction = false;
 
1444                         domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
 
1445                         final Map<String, String> functionParams = new HashMap<>();
 
1446                         functionParams.put("appId", String.valueOf(app.getId()));
 
1447                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1448                                 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);                        
 
1450                         if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
 
1451                                 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
 
1452                                         FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
 
1454                         domainCentralRoleFunction.setAppId(app.getId());
 
1455                         dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
 
1456                         saveOrUpdateFunction = true;
 
1457                 } catch (Exception e) {
 
1458                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
 
1461                 return saveOrUpdateFunction;
 
1465          * It creates application permission in external auth system
 
1467          * @param domainCentralRoleFunction
 
1471         private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
 
1473                 ObjectMapper mapper = new ObjectMapper();
 
1474                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
 
1475                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); 
 
1477                 String instance = "";
 
1479                 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
 
1480                         type =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType(); 
 
1481                         instance =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ?  EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
 
1482                         action =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
 
1484                         type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
 
1485                         instance = domainCentralRoleFunction.getCode();
 
1488                 // get Permissions from External Auth System
 
1489                 JSONArray extPermsList = getExtAuthPermissions(app);
 
1490                 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
 
1491                 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
 
1492                 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
 
1493                 if (!checkIfFunctionsExits) {
 
1495                                 extPerms.setAction(action);
 
1496                                 extPerms.setInstance(instance);
 
1497                                 extPerms.setType(app.getNameSpace() + "." + type);
 
1498                                 extPerms.setDescription(domainCentralRoleFunction.getName());
 
1499                                 String addFunction = mapper.writeValueAsString(extPerms);
 
1500                                 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
 
1501                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
 
1502                                 ResponseEntity<String> addPermResponse= template.exchange(
 
1503                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
 
1504                                                 HttpMethod.POST, entity, String.class);
 
1505                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
 
1506                         } catch(HttpClientErrorException e){
 
1507                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
 
1508                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1510                         }catch (Exception e) {
 
1511                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
 
1517                                 extPerms.setAction(action);
 
1518                                 extPerms.setInstance(instance);
 
1519                                 extPerms.setType(app.getNameSpace() + "." + type);
 
1520                                 extPerms.setDescription(domainCentralRoleFunction.getName());
 
1521                                 String updateRoleFunction = mapper.writeValueAsString(extPerms);
 
1522                                 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
 
1523                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
 
1524                                 ResponseEntity<String> updatePermResponse = template.exchange(
 
1525                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
 
1526                                                 HttpMethod.PUT, entity, String.class);
 
1527                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
 
1528                         } catch(HttpClientErrorException e){
 
1529                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
 
1530                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1532                         } catch (Exception e) {
 
1533                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
 
1539         @SuppressWarnings("unchecked")
 
1541         @Transactional(rollbackFor = Exception.class)
 
1542         public boolean deleteCentralRoleFunction(String code, EPApp app) {
 
1543                 boolean deleteFunctionResponse = false;
 
1545                         final Map<String, String> params = new HashMap<>();
 
1546                         params.put(FUNCTION_CODE_PARAMS, code);
 
1547                         params.put(APP_ID, String.valueOf(app.getId()));
 
1548                         List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
 
1549                                         .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
 
1550                         CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
 
1551                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1552                                 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
 
1553                                 // Delete role function dependency records
 
1554                                 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
 
1556                         dataAccessService.deleteDomainObject(appFunctionCode, null);
 
1557                         deleteFunctionResponse = true;
 
1558                 } catch (Exception e) {
 
1559                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
 
1561                 return deleteFunctionResponse;
 
1565          * It deletes app function record in portal 
 
1570         private void deleteAppRoleFunctions(String code, EPApp app) {
 
1571                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
 
1572                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
 
1577          * It deletes permission in the external auth system  
 
1579          * @param domainCentralRoleFunction
 
1583         private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
 
1586                         ObjectMapper mapper = new ObjectMapper();
 
1587                         ExternalAccessPerms extPerms = new ExternalAccessPerms();
 
1588                         String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
 
1589                         String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
 
1590                         String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
 
1591                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1592                         extPerms.setAction(actionValue);
 
1593                         extPerms.setInstance(instanceValue);
 
1594                         extPerms.setType(app.getNameSpace() + "." + checkType);
 
1595                         extPerms.setDescription(domainCentralRoleFunction.getName());
 
1596                         String deleteRoleFunction = mapper.writeValueAsString(extPerms);
 
1597                         HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
 
1598                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
 
1599                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
 
1600                         ResponseEntity<String> delPermResponse = template
 
1601                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1602                                                         + "perm?force=true", HttpMethod.DELETE, entity, String.class);
 
1603                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1604                                         "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
 
1605                                         deleteRoleFunction, delPermResponse.getStatusCode().value());
 
1606                 } catch(HttpClientErrorException e){
 
1607                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
 
1608                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1609                 } catch (Exception e) {
 
1610                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
 
1611                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1612                                                 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
 
1615                                 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
 
1621         public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
 
1622                 boolean response = false;
 
1623                 String message = "";
 
1625                         EPApp app = getApp(uebkey).get(0);
 
1626                         addRoleInEcompDB(saveRole, app);
 
1628                 } catch (Exception e) {
 
1629                         message = e.getMessage();
 
1630                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
 
1632                 return new ExternalRequestFieldsValidator(response,message);
 
1635         @SuppressWarnings("unchecked")
 
1637         public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
 
1638                 Session localSession = sessionFactory.openSession();
 
1639                 Transaction transaction = null;
 
1640                 boolean result = false;
 
1642                         List<EPRole> epRoleList = null;
 
1643                         EPApp app = getApp(uebkey).get(0);
 
1644                         final Map<String, String> deleteRoleParams = new HashMap<>();
 
1645                         deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
 
1646                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1647                                 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
 
1649                                 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
 
1650                                 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
 
1652                         if (!epRoleList.isEmpty()) {
 
1653                                 transaction = localSession.beginTransaction();
 
1654                                 // Delete app role functions before deleting role
 
1655                                 deleteRoleFunction(app, epRoleList);
 
1656                                 if (app.getId() == 1) {
 
1657                                         // Delete fn_user_ role
 
1658                                         dataAccessService.deleteDomainObjects(EPUserApp.class,
 
1659                                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
 
1660                                         boolean isPortalRequest = false;
 
1661                                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
 
1663                                 deleteRoleInExternalAuthSystem(epRoleList, app);
 
1664                                 transaction.commit();
 
1665                                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
 
1666                                 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
 
1669                 } catch (Exception e) {
 
1670                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
 
1673                         localSession.close();
 
1680          * It deletes role for application in external auth system 
 
1682          * @param epRoleList contains role information
 
1683          * @param app contains application information
 
1686         private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
 
1687                 ResponseEntity<String> deleteResponse;
 
1688                 ResponseEntity<String> res = getNameSpaceIfExists(app);
 
1689                 if (res.getStatusCode() == HttpStatus.OK) {
 
1690                 // Delete Role in External System
 
1691                 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
 
1692                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
 
1693                 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
 
1694                 if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
 
1695                         EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
 
1696                         logger.error(EELFLoggerDelegate.errorLogger,
 
1697                                         "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
 
1698                                         deleteResponse.getBody());
 
1700                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1701                                 "deleteRoleForApplication: about to commit the transaction");
 
1707          * It deletes application user role in external auth system
 
1714         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
 
1715                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
1716                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
1717                 getNameSpaceIfExists(app);
 
1718                 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
1719                 ResponseEntity<String> getResponse = template
 
1721                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
 
1724                                                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
 
1725                                                                 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
 
1726                                                 HttpMethod.GET, entity, String.class);
 
1727                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
 
1728                 if (getResponse.getStatusCode().value() != 200) {
 
1729                         throw new ExternalAuthSystemException(getResponse.getBody());
 
1731                 String res = getResponse.getBody();
 
1732                 if (!res.equals(IS_EMPTY_JSON_STRING)) {
 
1733                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
 
1734                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
1735                         ResponseEntity<String> deleteResponse = template
 
1737                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1738                                                                         + "userRole/" + LoginId
 
1740                                                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
 
1741                                                                         + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
 
1742                                                         HttpMethod.DELETE, userRoleentity, String.class);
 
1743                         if (deleteResponse.getStatusCode().value() != 200) {
 
1744                                 throw new ExternalAuthSystemException("Failed to delete user role");
 
1746                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
 
1750         @SuppressWarnings("unchecked")
 
1752         public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
 
1753                 List<CentralV2Role> roleList = new ArrayList<>();
 
1755                         List<EPApp> app = getApp(uebkey);
 
1756                         final Map<String, Long> params = new HashMap<>();
 
1759                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1760                                 appId = app.get(0).getId();
 
1762                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
 
1763                         Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
 
1766                                 appIdCrt = Restrictions.isNull("appId");
 
1768                                 appIdCrt = Restrictions.eq("appId", appId);
 
1769                         Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
 
1770                         restrictionsList.add(andCrit);
 
1771                         List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
 
1772                         roleList = createCentralRoleObject(app, epRole, roleList, params);
 
1773                         List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
 
1774                         if (globalRoleList.size() > 0)
 
1775                                 roleList.addAll(globalRoleList);
 
1776                 } catch (Exception e) {
 
1777                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
 
1785         @Transactional(rollbackFor = Exception.class)
 
1786         public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
 
1787                 Session localSession = sessionFactory.openSession();
 
1788                 String message = "";
 
1789                 Transaction transaction = null;
 
1790                 boolean response = false;
 
1793                         transaction = localSession.beginTransaction();
 
1794                         List<EPRole> epRoleList = null;
 
1795                         app = getApp(uebkey).get(0);
 
1796                         if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
1797                                 epRoleList = getPortalAppRoleInfo(roleId);
 
1799                                 epRoleList = getPartnerAppRoleInfo(roleId, app);
 
1801                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1802                                 // Delete User Role in External System before deleting role
 
1803                                 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);        
 
1805                         // Delete user app roles
 
1806                         dataAccessService.deleteDomainObjects(EPUserApp.class,
 
1807                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
 
1808                         boolean isPortalRequest = false;
 
1809                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
 
1810                         transaction.commit();
 
1811                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1812                                 // Final call to delete role once all dependencies has been deleted
 
1813                                 deleteRoleInExternalAuthSystem(epRoleList, app);
 
1815                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);            
 
1816                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
 
1818                 } catch(HttpClientErrorException e){
 
1819                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
 
1820                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
1821                         message = e.getMessage();
 
1822                 } catch (Exception e) {
 
1823                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
 
1824                         EcompPortalUtils.rollbackTransaction(transaction,
 
1825                                         "deleteDependencyRoleRecord rollback, exception = " + e.toString());
 
1826                         message = e.getMessage();
 
1828                         localSession.close();
 
1830                 return new ExternalRequestFieldsValidator(response,message);
 
1834         @SuppressWarnings("unchecked")
 
1836         public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
 
1839                         // get Permissions from External Auth System
 
1840                         JSONArray extPerms = getExtAuthPermissions(app);
 
1841                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
 
1843                         // get functions in DB
 
1844                         final Map<String, Long> params = new HashMap<>();
 
1845                         final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
 
1846                         params.put(APP_ID, app.getId());
 
1847                         List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
 
1849                         if (!appFunctions.isEmpty()) {
 
1850                                 for (CentralV2RoleFunction roleFunc : appFunctions) {
 
1851                                         roleFuncMap.put(roleFunc.getCode(), roleFunc);
 
1855                         // get Roles for portal in DB
 
1856                         List<EPRole> portalRoleList = getGlobalRolesOfPortal();
 
1857                         final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
 
1858                         for(EPRole epRole : portalRoleList){
 
1859                                 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
 
1863                         final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
 
1865                         // store External Permissions with Pipe and without Pipe (just instance)
 
1866                         final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
 
1867                         final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
 
1868                         for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
 
1869                                 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
 
1870                                 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
 
1871                                 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
 
1874                         // Add if new functions and app role functions were added in
 
1875                         // external auth system
 
1876                         for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
 
1877                                 String code = permsDetail.getInstance();
 
1878                                 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
 
1879                                 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
 
1880                                                 getFunctionCodeKey);
 
1881                                 List<String> roles = permsDetail.getRoles();
 
1882                                 if (roles != null) {
 
1883                                         // Check if function has any roles and which does not exist
 
1884                                         // in External Auth System. If exists delete in local
 
1885                                         addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
 
1889                         // Check if function does exits in External Auth System but exits in
 
1890                         // local then delete function and its dependencies
 
1891                         for (CentralV2RoleFunction roleFunc : appFunctions) {
 
1893                                         ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
 
1894                                                         .get(roleFunc.getCode());
 
1895                                         if (null == getFunctionCodeContainsPipeKey) {
 
1896                                                 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
 
1897                                                 if (null == getFunctionCodeKey) {
 
1898                                                         deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
 
1901                                 } catch (Exception e) {
 
1902                                         logger.error(EELFLoggerDelegate.errorLogger,
 
1903                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
 
1908                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1909                                         "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
 
1910                 } catch (Exception e) {
 
1911                         logger.error(EELFLoggerDelegate.errorLogger,
 
1912                                         "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
 
1917         @SuppressWarnings("unchecked")
 
1918         private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
 
1919                         List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
 
1921                 if (!roleFunctionList.isEmpty()) {
 
1922                         final Map<String, String> appRoleFuncParams = new HashMap<>();
 
1923                         final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
 
1924                         final Map<String, String> currentRolesInExtSystem = new HashMap<>();
 
1925                         appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
 
1926                         appRoleFuncParams.put("appId", String.valueOf(app.getId()));
 
1927                         List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
 
1928                                         appRoleFuncParams, null);
 
1929                         for (LocalRole localRole : localRoleList) {
 
1930                                 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
 
1931                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
 
1933                         for (String addRole : roles) {
 
1934                                 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
 
1936                         for (String extAuthrole : roles) {
 
1937                                 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
 
1938                                 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
 
1939                                 if (isNameSpaceMatching) {
 
1940                                         if (!currentAppRoleFunctionsMap
 
1941                                                         .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
 
1942                                                 EPRole localAddFuntionRole = currentRolesInDB
 
1943                                                                 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
 
1944                                                 if (localAddFuntionRole == null) {
 
1945                                                         checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
 
1947                                                         EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
 
1948                                                         addAppRoleFunc.setAppId(app.getId());
 
1949                                                         addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
 
1950                                                         addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
 
1951                                                         dataAccessService.saveDomainObject(addAppRoleFunc, null);
 
1954                                         // This block is to save global role function if exists
 
1956                                         String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
 
1957                                         boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
 
1958                                         if (checkIfGlobalRoleExists) {
 
1959                                                 final Map<String, Long> params = new HashMap<>();
 
1960                                                 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
 
1961                                                 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
 
1962                                                 params.put("appId", app.getId());
 
1963                                                 params.put("roleId", role.getId());
 
1964                                                 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);                               
 
1965                                                 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
 
1966                                                 if (role != null && !checkIfRoleFunctionExists) {
 
1967                                                         addGlobalRoleFunctions.setAppId(app.getId());
 
1968                                                         addGlobalRoleFunctions.setRoleId(role.getId());
 
1969                                                         if (!app.getId().equals(role.getAppRoleId())) {
 
1970                                                                 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
 
1972                                                                 addGlobalRoleFunctions.setRoleAppId(null);
 
1974                                                         addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
 
1975                                                         dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
 
1980                         for (LocalRole localRoleDelete : localRoleList) {
 
1981                                 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
 
1982                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
 
1983                                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
 
1984                                                         APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
 
1985                                                                         + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
 
1992         private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
 
1993                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1994                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
 
1995                                 roleFunc.getCode());
 
1996                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
 
1997                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
 
1998                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1999                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
 
2000                                 roleFunc.getCode());
 
2002                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2003                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
 
2004                                 roleFunc.getCode());
 
2005                 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
 
2006                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
 
2007                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2008                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
 
2009                                 roleFunc.getCode());
 
2012         private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
 
2013                         List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
 
2014                 if (!currentRolesInDB.containsKey(
 
2015                                 roleList.substring(app.getNameSpace().length() + 1))) {
 
2016                         Role role = addRoleInDBIfDoesNotExists(app,
 
2017                                         roleList.substring(app.getNameSpace().length() + 1));
 
2018                         addIfRoleDescriptionNotExitsInExtSystem(role, app);
 
2019                         if (!roleFunctionList.isEmpty()) {
 
2021                                         if (!roleFunctionList.isEmpty()) {
 
2022                                                 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
 
2023                                                 addAppRoleFunc.setAppId(app.getId());
 
2024                                                 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
 
2025                                                 addAppRoleFunc.setRoleId(role.getId());
 
2026                                                 dataAccessService.saveDomainObject(addAppRoleFunc, null);
 
2028                                 } catch (Exception e) {
 
2029                                         logger.error(EELFLoggerDelegate.errorLogger,
 
2030                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
 
2037         @SuppressWarnings("unchecked")
 
2038         private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
 
2039                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
 
2040                 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
 
2041                                 getFunctionCodeKey);
 
2042                 final Map<String, String> appSyncFuncsParams = new HashMap<>();
 
2043                 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
 
2044                 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
 
2045                 List<CentralV2RoleFunction> roleFunctionList = null;
 
2046                 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
 
2048                 if (roleFunctionList.isEmpty()) {
 
2049                         appSyncFuncsParams.put("functionCd", code);
 
2050                         roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
 
2053                 return roleFunctionList;
 
2056         private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
 
2057                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
 
2059                 String finalFunctionCodeVal = "";       
 
2060                 if (null == getFunctionCodeKey) {
 
2061                         finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
 
2062                         CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
 
2063                         // If function does not exist in local then add!
 
2064                         if (null == checkIfCodeStillExits) {
 
2065                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2066                                                 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
 
2067                                 addFunctionInEcompDB(app, permsDetail, code);
 
2068                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2069                                                 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
 
2072                 return finalFunctionCodeVal;
 
2075         @SuppressWarnings("unchecked")
 
2077         public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
 
2078                 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
 
2079                 List<EPRole> getCurrentRoleList = null;
 
2080                 final Map<String, Long> appParams = new HashMap<>();
 
2081                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2082                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
 
2084                         appParams.put("appId", app.getId());
 
2085                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
 
2087                 for (EPRole role : getCurrentRoleList) {
 
2088                         currentRolesInDB.put(role.getName()
 
2089                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
 
2091                 return currentRolesInDB;
 
2094         private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
 
2096                 ExternalAccessPermsDetail permDetails = null;
 
2097                 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
 
2098                 for (int i = 0; i < extPerms.length(); i++) {
 
2099                         String description = null;
 
2100                         if (extPerms.getJSONObject(i).has("description")) {
 
2101                                 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
 
2103                                 description = extPerms.getJSONObject(i).getString("type")+"|"+extPerms.getJSONObject(i).getString("instance")
 
2104                                                 +"|"+extPerms.getJSONObject(i).getString("action");
 
2106                         if (extPerms.getJSONObject(i).has("roles")) {
 
2107                                 ObjectMapper rolesListMapper = new ObjectMapper();
 
2108                                 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
 
2109                                 List<String> list = rolesListMapper.readValue(resRoles.toString(),
 
2110                                                 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
 
2111                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
 
2112                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
 
2113                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
 
2114                                                                 + extPerms.getJSONObject(i).getString("action"),
 
2115                                                 extPerms.getJSONObject(i).getString("action"), list, description);
 
2116                                 permsDetailList.add(permDetails);
 
2118                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
 
2119                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
 
2120                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
 
2121                                                                 + extPerms.getJSONObject(i).getString("action"),
 
2122                                                 extPerms.getJSONObject(i).getString("action"), description);
 
2123                                 permsDetailList.add(permDetails);
 
2126                 return permsDetailList;
 
2129         private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
 
2130                 ResponseEntity<String> response = null;
 
2131                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2132                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
2133                 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
 
2134                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
2136                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
2137                                                 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
 
2139                 String res = response.getBody();
 
2140                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2141                                 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
 
2142                                 response.getBody());
 
2143                 JSONObject jsonObj = new JSONObject(res);
 
2144                 JSONArray extPerms = jsonObj.getJSONArray("perm");
 
2145                 for (int i = 0; i < extPerms.length(); i++) {
 
2146                         if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
 
2156          * Add function into local DB
 
2159          * @param permsDetail
 
2162         private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
 
2164                 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
 
2165                 addFunction.setAppId(app.getId());
 
2166                 addFunction.setCode(code);
 
2167                 addFunction.setName(permsDetail.getDescription());
 
2168                 dataAccessService.saveDomainObject(addFunction, null);
 
2169                 } catch(Exception e){
 
2170                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
 
2176          * It updates description of a role in external auth system
 
2182         private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
 
2183                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
 
2184                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2186                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
 
2188                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
2189                                         HttpMethod.PUT, entity, String.class);
 
2190                 } catch (HttpClientErrorException e) {
 
2191                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
 
2193                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2194                 } catch (Exception e) {
 
2195                         logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
 
2202          * While sync functions form external auth system if new role found we should add in local and return Role.class object
 
2208         @SuppressWarnings("unchecked")
 
2209         private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
 
2210                 Role setNewRole = new Role();
 
2212                         // functions can have new role created in External Auth System prevent
 
2214                         boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
 
2215                         final Map<String, String> getRoleByNameParams = new HashMap<>();
 
2216                         List<EPRole> getRoleCreated = null;
 
2217                         getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
 
2218                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2219                                 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
 
2220                                 List<EPRole> roleCreated = dataAccessService
 
2221                                                 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
 
2223                                         EPRole epUpdateRole = roleCreated.get(0);
 
2224                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
 
2225                                         dataAccessService.saveDomainObject(epUpdateRole, null);
 
2226                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
 
2227                                                         getRoleByNameParams, null);
 
2229                                         getRoleCreated = roleCreated;
 
2232                                 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
 
2235                         if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
 
2236                                 EPRole roleObject = getRoleCreated.get(0);
 
2237                                 setNewRole.setId(roleObject.getId());
 
2238                                 setNewRole.setName(roleObject.getName());
 
2239                                 setNewRole.setActive(roleObject.getActive());
 
2240                                 setNewRole.setPriority(roleObject.getPriority());
 
2242                 } catch (Exception e) {
 
2243                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
 
2248         @SuppressWarnings("unchecked")
 
2249         private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
 
2250                 boolean isCreated = false;
 
2251                 final Map<String, String> roleParams = new HashMap<>();
 
2252                 roleParams.put(APP_ROLE_NAME_PARAM, role);
 
2253                 List<EPRole> roleCreated = null;
 
2254                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2255                         roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams,
 
2258                         roleParams.put("appId", String.valueOf(app.getId()));
 
2259                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
 
2262                 if (roleCreated == null || roleCreated.isEmpty()) {
 
2263                         roleParams.put("appId", String.valueOf(app.getId()));
 
2264                         EPRole epRoleNew = new EPRole();
 
2265                         epRoleNew.setActive(true);
 
2266                         epRoleNew.setName(role);
 
2267                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2268                                 epRoleNew.setAppId(null);
 
2270                                 epRoleNew.setAppId(app.getId());
 
2272                         dataAccessService.saveDomainObject(epRoleNew, null);
 
2281         @SuppressWarnings("unchecked")
 
2282         public Integer bulkUploadFunctions(String uebkey) throws Exception {
 
2283                 EPApp app = getApp(uebkey).get(0);
 
2284                 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
 
2285                 CentralV2RoleFunction cenRoleFunc = null;
 
2286                 Integer functionsAdded = 0;
 
2288                         for (RoleFunction roleFunc : roleFuncList) {
 
2289                                 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
 
2290                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
 
2293                 } catch(HttpClientErrorException e){
 
2294                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
 
2295                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2296                 } catch (Exception e) {
 
2297                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
 
2299                 return functionsAdded;
 
2303         public Integer bulkUploadRoles(String uebkey) throws Exception {
 
2304                 List<EPApp> app = getApp(uebkey);
 
2305                 List<EPRole> roles = getAppRoles(app.get(0).getId());
 
2306                 List<CentralV2Role> cenRoleList = new ArrayList<>();
 
2307                 final Map<String, Long> params = new HashMap<>();
 
2308                 Integer rolesListAdded = 0;
 
2310                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
 
2311                         ObjectMapper mapper = new ObjectMapper();
 
2312                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
 
2313                         String roleList = mapper.writeValueAsString(cenRoleList);
 
2314                         List<Role> roleObjectList = mapper.readValue(roleList,
 
2315                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
 
2316                         for (Role role : roleObjectList) {
 
2317                                 addRoleInExternalSystem(role, app.get(0));
 
2320                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2321                                 // Add Account Admin role in External AUTH System
 
2323                                         String addAccountAdminRole = "";
 
2324                                         ExternalAccessRole extRole = new ExternalAccessRole();
 
2325                                         extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
 
2326                                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
2327                                         addAccountAdminRole = mapper.writeValueAsString(extRole);
 
2328                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2329                                         HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
 
2331                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
2332                                                         HttpMethod.POST, entity, String.class);
 
2334                                 } catch (HttpClientErrorException e) {
 
2335                                         logger.error(EELFLoggerDelegate.errorLogger,
 
2336                                                         "HttpClientErrorException - Failed to create Account Admin role", e);
 
2337                                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2338                                 } catch (Exception e) {
 
2339                                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
2340                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2341                                                                 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
 
2344                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2345                                                                 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
 
2349                 } catch (Exception e) {
 
2350                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
 
2353                 return rolesListAdded;
 
2357          * It creating new role in external auth system while doing bulk upload
 
2363         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
 
2364                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
 
2365                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2367                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
 
2369                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
 
2370                                         HttpMethod.POST, entity, String.class);
 
2371                 } catch(HttpClientErrorException e){
 
2372                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
 
2373                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2374                 } catch (Exception e) {
 
2375                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
2376                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
 
2378                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
 
2384         @SuppressWarnings("unchecked")
 
2385         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
 
2386                 EPApp app = getApp(uebkey).get(0);
 
2387                 List<EPRole> roles = getAppRoles(app.getId());
 
2388                 final Map<String, Long> params = new HashMap<>();
 
2389                 Integer roleFunctions = 0;
 
2391                         for (EPRole role : roles) {
 
2392                                 params.put("roleId", role.getId());
 
2393                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
 
2395                                 if (!appRoleFunc.isEmpty()) {
 
2396                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
 
2397                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
 
2402                 } catch(HttpClientErrorException e){
 
2403                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
 
2404                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2405                 } catch (Exception e) {
 
2406                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
 
2408                 return roleFunctions;
 
2412          * Its adding a role function while doing bulk upload
 
2414          * @param addRoleFunc
 
2418         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
 
2420                 String instance = "";
 
2422                 if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){
 
2423                         type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd()); 
 
2424                         instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
 
2425                         action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
 
2427                         type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
 
2428                         instance = addRoleFunc.getFunctionCd();
 
2431                 ExternalAccessRolePerms extRolePerms = null;
 
2432                 ExternalAccessPerms extPerms = null;
 
2433                 ObjectMapper mapper = new ObjectMapper();
 
2435                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2436                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
 
2437                                         addRoleFunc.getFunctionName());
 
2438                         extRolePerms = new ExternalAccessRolePerms(extPerms,
 
2439                                         app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
2440                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
2441                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
2443                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
 
2444                                         HttpMethod.POST, entity, String.class);
 
2445                 } catch (Exception e) {
 
2446                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
2447                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2448                                                 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
 
2450                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
 
2456         @SuppressWarnings("unchecked")
 
2458         public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
 
2459                 EPApp app = getApp(uebkey).get(0);
 
2460                 final Map<String, Long> params = new HashMap<>();
 
2461                 params.put("appId", app.getId());
 
2462                 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
 
2464                 Integer functionsAdded = 0;
 
2466                         for (CentralV2RoleFunction roleFunc : roleFuncList) {
 
2467                                 addFunctionInExternalSystem(roleFunc, app);
 
2470                 } catch (HttpClientErrorException e) {
 
2471                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e);
 
2472                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2473                 } catch (Exception e) {
 
2474                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
 
2476                 return functionsAdded;
 
2479         private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
 
2480                 ObjectMapper mapper = new ObjectMapper();
 
2481                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
 
2482                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2484                 String instance = "";
 
2486                 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
 
2487                                 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
 
2488                         type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
 
2489                         instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
 
2490                         action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
 
2492                         type = roleFunc.getCode().contains("menu") ? "menu" : "url";
 
2493                         instance = roleFunc.getCode();
 
2497                         extPerms.setAction(action);
 
2498                         extPerms.setInstance(instance);
 
2499                         extPerms.setType(app.getNameSpace() + "." + type);
 
2500                         extPerms.setDescription(roleFunc.getName());
 
2501                         String addFunction = mapper.writeValueAsString(extPerms);
 
2502                         HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
 
2503                         logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
 
2504                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
 
2505                         ResponseEntity<String> addPermResponse = template.exchange(
 
2506                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
 
2507                                         HttpMethod.POST, entity, String.class);
 
2508                         logger.debug(EELFLoggerDelegate.debugLogger,
 
2509                                         "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
 
2510                                         addPermResponse.getStatusCode().value(), addFunction);
 
2511                 } catch (HttpClientErrorException e) {
 
2512                         logger.error(EELFLoggerDelegate.errorLogger,
 
2513                                         "HttpClientErrorException - Failed to add function in external central auth system", e);
 
2514                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2516                 } catch (Exception e) {
 
2517                         logger.error(EELFLoggerDelegate.errorLogger,
 
2518                                         "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
 
2524         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
 
2525                 EPApp app = getApp(uebkey).get(0);
 
2526                 for (Role role : roleList) {
 
2527                         addRoleInExternalSystem(role, app);
 
2531         @SuppressWarnings("unchecked")
 
2533         public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
 
2534                 EPApp app = getApp(uebkey).get(0);
 
2535                 List<EPRole> roles = getAppRoles(app.getId());
 
2536                 final Map<String, Long> params = new HashMap<>();
 
2537                 Integer roleFunctions = 0;
 
2539                         for (EPRole role : roles) {
 
2540                                 params.put("roleId", role.getId());
 
2541                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions",
 
2543                                 if (!appRoleFunc.isEmpty()) {
 
2544                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
 
2545                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
 
2550                         // upload global role functions to ext auth system
 
2551                         if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2552                                 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
 
2554                 } catch(HttpClientErrorException e){
 
2555                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
 
2556                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2557                 } catch (Exception e) {
 
2558                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
 
2560                 return roleFunctions;
 
2563         @SuppressWarnings("unchecked")
 
2564         private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
 
2566                         EPApp portalApp = epAppService.getApp(1l);
 
2567                         final Map<String, Long> params = new HashMap<>();
 
2568                         params.put("appId", app.getId());
 
2569                         List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
 
2570                                         .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
 
2571                         ObjectMapper mapper = new ObjectMapper();
 
2572                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2573                         for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
 
2574                                 ExternalAccessRolePerms extRolePerms;
 
2575                                 ExternalAccessPerms extPerms;
 
2577                                 String instance = "";
 
2579                                 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
 
2580                                         type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
 
2581                                         instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
 
2582                                         action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
 
2584                                         type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
 
2585                                         instance = globalRoleFunc.getFunctionCd();
 
2588                                 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
 
2589                                 extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName()
 
2590                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
2591                                 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
2592                                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
2593                                 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
 
2596                 } catch (HttpClientErrorException e) {
 
2597                         logger.error(EELFLoggerDelegate.errorLogger,
 
2598                                         "HttpClientErrorException - Failed to add role function in external central auth system", e);
 
2599                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2601                 } catch (Exception e) {
 
2602                         logger.error(EELFLoggerDelegate.errorLogger,
 
2603                                         "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
 
2606                 return roleFunctions;
 
2611         public void syncApplicationRolesWithEcompDB(EPApp app) {
 
2613                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
 
2614                         //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
 
2615                         syncRoleFunctionFromExternalAccessSystem(app);
 
2616                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");     
 
2618                         ObjectMapper mapper = new ObjectMapper();
 
2619                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
 
2620                         // Get Permissions from External Auth System
 
2621                         JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
 
2623                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
 
2625                         List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
 
2628                         List<EPRole> finalRoleList = new ArrayList<>();
 
2629                         for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
 
2630                                 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
 
2631                                 finalRoleList.add(ecompRole);
 
2634                         List<EPRole> applicationRolesList;
 
2635                         applicationRolesList = getAppRoles(app.getId());
 
2636                         List<String> applicationRoleIdList = new ArrayList<>();
 
2637                         for (EPRole applicationRole : applicationRolesList) {
 
2638                                 applicationRoleIdList.add(applicationRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
2641                         List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
 
2642                         for (EPRole aafRole : finalRoleList) {
 
2643                                 if (!applicationRoleIdList.contains(aafRole.getName())) {
 
2644                                         roleListToBeAddInEcompDB.add(aafRole);
 
2648                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
 
2649                         // Check if roles exits in external Access system and if not make inactive in DB
 
2650                         inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
 
2652                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
 
2653                         // It checks properties in the external auth system app role description and updates role in local
 
2654                         checkAndUpdateRoleInDB(app, finalRoleList);
 
2656                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
 
2657                         // Add new roles in DB and updates role description in External Auth System 
 
2658                         addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
 
2659                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
 
2660                 } catch (HttpClientErrorException e) {
 
2661                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
 
2662                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
2663                 } catch (Exception e) {
 
2664                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
 
2670          * It adds new roles in DB and updates description in External Auth System
 
2673          * @param roleListToBeAddInEcompDB
 
2675         @SuppressWarnings("unchecked")
 
2676         private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
 
2677                 EPRole roleToBeAddedInEcompDB;
 
2678                 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
 
2680                                 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
 
2681                                 if (app.getId() == 1) {
 
2682                                         roleToBeAddedInEcompDB.setAppRoleId(null);
 
2684                                 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
 
2685                                 List<EPRole> getRoleCreatedInSync = null;
 
2686                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
2687                                         final Map<String, String> globalRoleParams = new HashMap<>();
 
2688                                         globalRoleParams.put("appId", String.valueOf(app.getId()));
 
2689                                         globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
 
2690                                         getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
 
2691                                         EPRole epUpdateRole = getRoleCreatedInSync.get(0);
 
2692                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
 
2693                                         dataAccessService.saveDomainObject(epUpdateRole, null);
 
2695                                 List<EPRole> roleList = new ArrayList<>();
 
2696                                 final Map<String, String> params = new HashMap<>();
 
2698                                 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
 
2699                                 boolean isPortalRole = false;
 
2700                                 if (app.getId() == 1) {
 
2701                                         isPortalRole = true;
 
2702                                         roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
 
2704                                         isPortalRole = false;
 
2705                                         params.put(APP_ID, app.getId().toString());
 
2706                                         roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
 
2708                                 EPRole role = roleList.get(0);
 
2709                                 Role aaFrole = new Role();
 
2710                                 aaFrole.setId(role.getId());
 
2711                                 aaFrole.setActive(role.getActive());
 
2712                                 aaFrole.setPriority(role.getPriority());
 
2713                                 aaFrole.setName(role.getName());
 
2714                                 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
 
2715                         } catch (Exception e) {
 
2716                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2717                                                 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
 
2724          * It checks description in External Auth System if found any changes updates in DB
 
2727          * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
 
2729         @SuppressWarnings("unchecked")
 
2730         private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
 
2731                 for (EPRole roleItem : finalRoleList) {
 
2732                         final Map<String, String> roleParams = new HashMap<>();
 
2733                         List<EPRole> currentList = null;
 
2734                         roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
 
2735                         if (app.getId() == 1) {
 
2736                                 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
 
2738                                 roleParams.put(APP_ID, app.getId().toString());
 
2739                                 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
 
2742                         if (!currentList.isEmpty()) {
 
2744                                         Boolean aafRoleActive;
 
2745                                         Boolean localRoleActive;
 
2747                                         aafRoleActive = Boolean.valueOf(roleItem.getActive());
 
2748                                         localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
 
2749                                         result = aafRoleActive.equals(localRoleActive);
 
2750                                         EPRole updateRole = currentList.get(0);
 
2753                                                 updateRole.setActive(roleItem.getActive());
 
2754                                                 dataAccessService.saveDomainObject(updateRole, null);
 
2756                                         if (roleItem.getPriority() != null
 
2757                                                         && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
 
2758                                                 updateRole.setPriority(roleItem.getPriority());
 
2759                                                 dataAccessService.saveDomainObject(updateRole, null);
 
2761                                 } catch (Exception e) {
 
2762                                         logger.error(EELFLoggerDelegate.errorLogger,
 
2763                                                         "syncApplicationRolesWithEcompDB: Failed to update role ", e);
 
2770          * It de-activates application roles in DB if not present in External Auth system  
 
2773          * @param finalRoleList contains list of current roles present in External Auth System
 
2774          * @param applicationRolesList contains list of current roles present in DB
 
2776         @SuppressWarnings("unchecked")
 
2777         private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
 
2778                         List<EPRole> applicationRolesList) {
 
2779                 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
 
2780                 for (EPRole extrole : finalRoleList) {
 
2781                         checkRolesInactive.put(extrole.getName(), extrole);
 
2783                 for (EPRole role : applicationRolesList) {
 
2785                                 final Map<String, String> extRoleParams = new HashMap<>();
 
2786                                 List<EPRole> roleList = null;
 
2787                                 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
 
2788                                 if (!checkRolesInactive.containsKey(role.getName())) {
 
2789                                         if (app.getId() == 1) {
 
2790                                                 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
 
2792                                                 extRoleParams.put(APP_ID, app.getId().toString());
 
2793                                                 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
 
2795                                         if(!roleList.isEmpty()) {
 
2796                                                 EPRole updateRoleInactive = roleList.get(0);
 
2797                                                 updateRoleInactive.setActive(false);
 
2798                                                 dataAccessService.saveDomainObject(updateRoleInactive, null);
 
2801                         } catch (Exception e) {
 
2802                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2803                                                 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
 
2809         @SuppressWarnings("unchecked")
 
2810         public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
 
2811                         ObjectMapper mapper, JSONArray extRole)
 
2812                         throws IOException {
 
2813                 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
 
2814                 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
 
2815                 List<String> functionCodelist = new ArrayList<>();
 
2816                 Map<String, EPRole> curRolesMap = getCurrentRolesInDB(app);
 
2817                 for (int i = 0; i < extRole.length(); i++) {
 
2818                         ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
 
2819                         EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
 
2820                         JSONObject Role = (JSONObject) extRole.get(i);
 
2821                         String name = extRole.getJSONObject(i).getString(ROLE_NAME);
 
2822                         String actualRoleName = name.substring(app.getNameSpace().length() + 1); 
 
2823                         SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
 
2824                         if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
 
2825                                 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
 
2826                                 for (int j = 0; j < extPerm.length(); j++) {
 
2827                                         JSONObject perms = extPerm.getJSONObject(j);
 
2828                                         boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
 
2829                                                         app.getNameSpace());
 
2830                                         if (isNamespaceMatching) {
 
2831                                                 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
 
2832                                                                 perms.getString("instance"), perms.getString("action"));
 
2833                                                 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
 
2834                                                 functionCodelist.add(ePAppRoleFunction.getCode());
 
2835                                                 externalAccessPermsOfRole.add(externalAccessPerms);
 
2840                         externalRoleDetail.setActive(true);
 
2841                         externalRoleDetail.setName(actualRoleName);
 
2842                         if (app.getId() == 1) {
 
2843                                 externalRoleDetail.setAppId(null);
 
2845                                 externalRoleDetail.setAppId(app.getId());
 
2847                         // get role functions from DB
 
2848                         EPRole currRole = curRolesMap.get(actualRoleName
 
2849                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
2851                         if (currRole != null)
 
2852                                 roleId = currRole.getId();
 
2853                         // get role functions from DB
 
2854                         final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
 
2855                         final Map<String, Long> appRoleFuncsParams = new HashMap<>();
 
2856                         if (roleId != null) {
 
2857                                 appRoleFuncsParams.put("appId", app.getId());
 
2858                                 appRoleFuncsParams.put("roleId", roleId);
 
2859                                 List<EPAppRoleFunction> appRoleFunctions = dataAccessService
 
2860                                                 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
 
2861                                 if (!appRoleFunctions.isEmpty()) {
 
2862                                         for (EPAppRoleFunction roleFunc : appRoleFunctions) {
 
2863                                                 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
 
2867                         if (!externalAccessPermsOfRole.isEmpty()) {
 
2868                                 // Adding functions to role
 
2869                                 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
 
2870                                         EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
 
2871                                         if (checkRoleFunctionExits == null) {
 
2872                                                 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
 
2873                                                                 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
 
2874                                                                 + externalpermission.getAction();
 
2875                                                 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
 
2876                                                 if (checkRoleFunctionPipeExits == null) {
 
2878                                                                 final Map<String, String> appFuncsParams = new HashMap<>();
 
2879                                                                 appFuncsParams.put("appId", String.valueOf(app.getId()));
 
2880                                                                 appFuncsParams.put("functionCd", externalpermission.getInstance());
 
2881                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2882                                                                                 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
 
2883                                                                                 externalpermission.getInstance());
 
2884                                                                 List<CentralV2RoleFunction> roleFunction = null;
 
2885                                                                 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
 
2886                                                                                 appFuncsParams, null);
 
2887                                                                 if (roleFunction.isEmpty()) {
 
2888                                                                         appFuncsParams.put("functionCd", funcCode);
 
2889                                                                         roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
 
2890                                                                                         appFuncsParams, null);
 
2892                                                                 if (!roleFunction.isEmpty()) {
 
2893                                                                         EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
 
2894                                                                         apRoleFunction.setAppId(app.getId());
 
2895                                                                         apRoleFunction.setRoleId(roleId);
 
2896                                                                         apRoleFunction.setCode(roleFunction.get(0).getCode());
 
2897                                                                         dataAccessService.saveDomainObject(apRoleFunction, null);
 
2899                                                         } catch (Exception e) {
 
2900                                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
2901                                                                                 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
 
2907                         externalRoleDetailsList.add(externalRoleDetail);
 
2909                 return externalRoleDetailsList;
 
2913         public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
 
2914                 ResponseEntity<String> response = null;
 
2915                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2916                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
2917                 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
 
2918                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
2920                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
2921                                                 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
 
2922                 String res = response.getBody();
 
2923                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2924                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
 
2926                 JSONObject jsonObj = new JSONObject(res);
 
2927                 JSONArray extRole = jsonObj.getJSONArray("role");
 
2928                 for (int i = 0; i < extRole.length(); i++) {
 
2929                         if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
 
2930                                         || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
 
2931                                         || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
 
2932                                                         && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
 
2941         public JSONArray getAllUsersByRole(String roleName) throws Exception{
 
2942                 ResponseEntity<String> response = null;
 
2943                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
2944                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
2945                 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
 
2946                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
 
2948                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
2949                                                 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
 
2950                 String res = response.getBody();
 
2951                 logger.debug(EELFLoggerDelegate.debugLogger,
 
2952                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
 
2954                 if(res == null || res.trim().isEmpty()) 
 
2957                 JSONObject jsonObj = new JSONObject(res);
 
2958                 JSONArray extRole = jsonObj.getJSONArray("userRole");
 
2965          * It converts from ExternalRoleDetails.class object to EPRole.class object
 
2967          * @param externalRoleDetails
 
2968          * @return EPRole object
 
2970         private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
 
2971                 EPRole role = new EPRole();
 
2972                 role.setActive(true);
 
2973                 role.setAppId(externalRoleDetails.getAppId());
 
2974                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
 
2975                 role.setName(externalRoleDetails.getName());
 
2976                 role.setPriority(externalRoleDetails.getPriority());
 
2980         @SuppressWarnings("unchecked")
 
2982         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
 
2983                 EPApp app = getApp(uebkey).get(0);
 
2984                 final Map<String, String> params = new HashMap<>();
 
2985                 params.put("uebKey", app.getUebKey());
 
2986                 List<BulkUploadUserRoles> userRolesList = null;
 
2987                 Integer userRolesAdded = 0;
 
2988                 if (app.getCentralAuth()) {
 
2989                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
 
2990                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
 
2991                                 if(!userRolesUpload.getOrgUserId().equals("su1234")){
 
2992                                         addUserRoleInExternalSystem(userRolesUpload);
 
2997                 return userRolesAdded;
 
3001          * Its adding a user role in external auth system while doing bulk upload 
 
3003          * @param userRolesUpload
 
3005         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
 
3008                         ObjectMapper mapper = new ObjectMapper();
 
3009                         if (EPCommonSystemProperties
 
3010                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
 
3011                                 name = userRolesUpload.getOrgUserId()
 
3012                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
 
3014                         ExternalAccessUser extUser = new ExternalAccessUser(name,
 
3015                                         userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
3016                         String userRole = mapper.writeValueAsString(extUser);
 
3017                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
3018                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
 
3020                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
 
3021                                         HttpMethod.POST, entity, String.class);
 
3022                 } catch(HttpClientErrorException e){
 
3023                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
 
3024                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
3025                 } catch (Exception e) {
 
3026                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
 
3027                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
 
3029                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
 
3035         public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
 
3040                         //It should delete only when it portal's roleId
 
3041                         if(appId.equals(PortalConstants.PORTAL_APP_ID)){
 
3042                         // Delete from fn_role_function
 
3043                         sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
 
3044                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3045                         query = localSession.createSQLQuery(sql);
 
3046                         query.executeUpdate();
 
3048                         // Delete from fn_role_composite
 
3049                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
 
3050                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3051                         query = localSession.createSQLQuery(sql);
 
3052                         query.executeUpdate();
 
3055                         // Delete from ep_app_role_function
 
3056                         sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
 
3057                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3058                         query = localSession.createSQLQuery(sql);
 
3059                         query.executeUpdate();
 
3061                         // Delete from ep_role_notification
 
3062                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
 
3063                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3064                         query = localSession.createSQLQuery(sql);
 
3065                         query.executeUpdate();
 
3067                         // Delete from fn_user_pseudo_role
 
3068                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
 
3069                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3070                         query = localSession.createSQLQuery(sql);
 
3071                         query.executeUpdate();
 
3073                         // Delete form EP_WIDGET_CATALOG_ROLE
 
3074                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
 
3075                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3076                         query = localSession.createSQLQuery(sql);
 
3077                         query.executeUpdate();
 
3079                         // Delete form EP_WIDGET_CATALOG_ROLE
 
3080                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
 
3081                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3082                         query = localSession.createSQLQuery(sql);
 
3083                         query.executeUpdate();
 
3085                         if(!isPortalRequest) {
 
3086                                 // Delete form fn_menu_functional_roles
 
3087                                 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
 
3088                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
3089                                 query = localSession.createSQLQuery(sql);
 
3090                                 query.executeUpdate();  
 
3092                 } catch (Exception e) {
 
3093                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
 
3094                         throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
 
3099         @SuppressWarnings("unchecked")
 
3101         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
 
3102                 List<String> appMenuFunctionsList = null;
 
3103                 List<String> appMenuFunctionsFinalList = new ArrayList<>();
 
3105                         EPApp app = getApp(uebkey).get(0);
 
3106                         final Map<String, Long> appParams = new HashMap<>();
 
3107                         appParams.put(APP_ID, app.getId());
 
3108                         appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
 
3109                         for(String appMenuFunction : appMenuFunctionsList) {
 
3110                                 if(appMenuFunction.contains(FUNCTION_PIPE)) {
 
3111                                         appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
 
3113                                         appMenuFunctionsFinalList.add(appMenuFunction);
 
3116                 } catch (Exception e) {
 
3117                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
 
3118                         return appMenuFunctionsFinalList;
 
3120                 return appMenuFunctionsFinalList;
 
3123         @SuppressWarnings({ "unchecked"})
 
3125         public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
 
3126                 List<String> usersList = new ArrayList<>();
 
3127         List<EcompUser> usersfinalList = new ArrayList<>();
 
3129                EPApp app = getApp(uebkey).get(0);
 
3130                final Map<String, Long> appParams = new HashMap<>();
 
3131                appParams.put("appId", app.getId());
 
3132                List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
 
3133                             .executeNamedQuery("ApplicationUserRoles", appParams, null);
 
3134                for (EcompUserRoles ecompUserRole : userList) {
 
3135                      boolean found = false;
 
3136                      Set<EcompRole> roles = null;
 
3137                      for (EcompUser user : usersfinalList) {
 
3138                             if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
 
3139                                    EcompRole ecompRole = new EcompRole();
 
3140                                    ecompRole.setId(ecompUserRole.getRoleId());
 
3141                                    ecompRole.setName(ecompUserRole.getRoleName());
 
3142                                    roles = user.getRoles();
 
3143                                    EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny()
 
3145                                    SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
 
3148                                           roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
 
3151                              String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
 
3152                             functionCode = EPUserUtils.decodeFunctionCode(functionCode);
 
3153                             EcompRoleFunction epRoleFunction = new EcompRoleFunction();
 
3154                             epRoleFunction.setName(ecompUserRole.getFunctionName());
 
3155                             epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
 
3156                             epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
 
3157                             epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
 
3158                             roleFunctionSet.add(epRoleFunction);
 
3159                         ecompRole.setRoleFunctions(roleFunctionSet);
 
3160                                    roles.add(ecompRole);
 
3161                                    user.setRoles(roles);
 
3168                             EcompUser epUser = new EcompUser();
 
3169                             epUser.setOrgId(ecompUserRole.getOrgId());
 
3170                             epUser.setManagerId(ecompUserRole.getManagerId());
 
3171                             epUser.setFirstName(ecompUserRole.getFirstName());
 
3172                             epUser.setLastName(ecompUserRole.getLastName());
 
3173                             epUser.setPhone(ecompUserRole.getPhone());
 
3174                             epUser.setEmail(ecompUserRole.getEmail());
 
3175                             epUser.setOrgUserId(ecompUserRole.getOrgUserId());
 
3176                             epUser.setOrgCode(ecompUserRole.getOrgCode());
 
3177                             epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
 
3178                             epUser.setJobTitle(ecompUserRole.getJobTitle());
 
3179                             epUser.setLoginId(ecompUserRole.getLoginId());
 
3180                             epUser.setActive(true);
 
3181                             roles = new HashSet<>();
 
3182                             EcompRole ecompRole = new EcompRole();
 
3183                             ecompRole.setId(ecompUserRole.getRoleId());
 
3184                             ecompRole.setName(ecompUserRole.getRoleName());
 
3185               SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
 
3187                             String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
 
3188               functionCode = EPUserUtils.decodeFunctionCode(functionCode);
 
3189               EcompRoleFunction epRoleFunction = new EcompRoleFunction();
 
3190               epRoleFunction.setName(ecompUserRole.getFunctionName());
 
3191               epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
 
3192               epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
 
3193               epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
 
3194               roleFunctionSet.add(epRoleFunction);
 
3195               ecompRole.setRoleFunctions(roleFunctionSet);
 
3196                             roles.add(ecompRole);
 
3197                             epUser.setRoles(roles);
 
3198                             usersfinalList.add(epUser);
 
3201                ObjectMapper mapper = new ObjectMapper();
 
3203                for (EcompUser u1 : usersfinalList) {
 
3204                      String str = mapper.writeValueAsString(u1);
 
3207         } catch (Exception e) {
 
3208                logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
 
3211         return usersfinalList;
 
3217         public Role ConvertCentralRoleToRole(String result) {
 
3218                 ObjectMapper mapper = new ObjectMapper();
 
3219                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
3220                 Role newRole = new Role();
 
3222                         newRole = mapper.readValue(result, Role.class);
 
3223                 } catch (IOException e) {
 
3224                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
 
3226                 if (newRole.getRoleFunctions() != null) {
 
3227                         @SuppressWarnings("unchecked")
 
3228                         Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
 
3229                         Set<RoleFunction> roleFunctionListNew = new HashSet<>();
 
3230                         Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
 
3231                         while (itetaror.hasNext()) {
 
3232                                 Object nextValue = itetaror.next();
 
3233                                 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
 
3234                                 roleFunctionListNew.add(roleFun);
 
3236                         newRole.setRoleFunctions(roleFunctionListNew);
 
3242         @SuppressWarnings("unchecked")
 
3243         public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
 
3244                 Map<String, String> params = new HashMap<>();
 
3245                 params.put("userId", userId);
 
3246                 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
 
3248                         centralizedAppsList =  dataAccessService
 
3249                                         .executeNamedQuery("getCentralizedAppsOfUser", params, null);
 
3250                 }catch (Exception e) {
 
3251                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
 
3253                 return centralizedAppsList;
 
3256         @SuppressWarnings("unchecked")
 
3257         public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
 
3258                 Map<String, Long> params = new HashMap<>();
 
3259                 params.put("appId", appId);
 
3260                 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
 
3262                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
 
3264                 } catch (Exception e) {
 
3265                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
 
3267                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
 
3268                 if (globalRoles.size() > 0)
 
3269                         rolesfinalList = finalListOfCentralRoles(globalRoles);
 
3270                 return rolesfinalList;
 
3273         @SuppressWarnings("unchecked")
 
3274         private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
 
3275                 CentralV2Role finalGlobalrole = null;
 
3276                 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
 
3277                 Map<String, Long> params = new HashMap<>();
 
3278                 params.put("roleId", roleId);
 
3279                 params.put("requestedAppId", requestedAppId);
 
3281                         roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
 
3283                 } catch (Exception e) {
 
3284                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
 
3286                 if (roleWithApplicationRoleFucntions.size() > 0) {
 
3287                         List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
 
3288                         finalGlobalrole = rolesfinalList.get(0);
 
3290                         List<EPRole> roleList = getPortalAppRoleInfo(roleId);
 
3291                         finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
 
3293                 return finalGlobalrole;
 
3296         private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
 
3297                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
 
3298                 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
 
3299                         boolean found = false;
 
3300                         for (CentralV2Role cenRole : rolesfinalList) {
 
3301                                 if (role.getRoleId().equals(cenRole.getId())) {
 
3302                                         SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
 
3303                                         CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
 
3304                                         roleFunctions.add(cenRoleFun);
 
3305                                         cenRole.setRoleFunctions(roleFunctions);
 
3311                                 CentralV2Role cenrole = new CentralV2Role();
 
3312                                 cenrole.setName(role.getRoleName());
 
3313                                 cenrole.setId(role.getRoleId());
 
3314                                 cenrole.setActive(role.isActive());
 
3315                                 cenrole.setPriority(role.getPriority());
 
3316                                 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
 
3317                                 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
 
3318                                 roleFunctions.add(cenRoleFun);
 
3319                                 cenrole.setRoleFunctions(roleFunctions);
 
3320                                 rolesfinalList.add(cenrole);
 
3323                 return rolesfinalList;
 
3326         private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
 
3330                 CentralV2RoleFunction cenRoleFun;
 
3331                 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
 
3332                         instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
 
3333                         type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
 
3334                         action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
 
3335                         cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
 
3337                         type = getFunctionCodeType(role.getFunctionCd());
 
3338                         action = getFunctionCodeAction(role.getFunctionCd());
 
3339                         cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
 
3344         @SuppressWarnings("unchecked")
 
3346         public List<EPRole> getGlobalRolesOfPortal() {
 
3347                 List<EPRole> globalRoles = new ArrayList<>();
 
3349                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
 
3350                 } catch (Exception e) {
 
3351                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
 
3356         private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
 
3357          return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
 
3358                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
 
3359                                 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
 
3364         public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
 
3365                 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
 
3366                 for(CentralV2RoleFunction cenRoleFunc : answer){
 
3367                         CentralRoleFunction setRoleFunc = new CentralRoleFunction();
 
3368                         setRoleFunc.setCode(cenRoleFunc.getCode());
 
3369                         setRoleFunc.setName(cenRoleFunc.getName());
 
3370                         addRoleFuncList.add(setRoleFunc);
 
3372                 return addRoleFuncList;
 
3376         public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
 
3377                 CentralUser sendUserRoles = null;
 
3380                         CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
 
3381                         sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
 
3382                 } catch (Exception e) {
 
3383                         logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
 
3386                 return sendUserRoles;
 
3391          * It returns V2 CentralUser object if user has any roles and permissions
 
3395          * @return CentralUser object
 
3398         private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
 
3400                 List<EPUser> epUserList;
 
3401                 List<EPApp> appList = getApp(uebkey);
 
3402                 app = appList.get(0);
 
3403                 epUserList = getUser(loginId);
 
3404                 EPUser user = epUserList.get(0);
 
3405                 Set<EPUserApp> userAppSet = user.getEPUserApps();
 
3406                 return createEPUser(user, userAppSet, app);
 
3410          * It converts V2 CentralUser object to old version CentralUser object
 
3413          * @return EPUser object
 
3415         private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
 
3416                         Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
 
3417                         Set<CentralUserApp> userApps = new TreeSet<>();
 
3418                         for(CentralV2UserApp userApp : userV2Apps){                             
 
3419                                 CentralApp app  = userApp.getApp();
 
3420                                 CentralUserApp cua = new CentralUserApp();
 
3421                                 cua.setUserId(null);
 
3423                                 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
 
3424                                 for(CentralV2RoleFunction  cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){                                      
 
3425                                         CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());                                                            
 
3426                                         cenRoleFunction.add(cenRoleFunc);
 
3428                                 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(),
 
3433                         return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(), 
 
3434                                         cenV2User.getCreatedId(),cenV2User.getModifiedId(), 
 
3435                                         cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(), 
 
3436                                         cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), 
 
3437                                         cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
 
3438                                         cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(), 
 
3439                                         cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(), 
 
3440                                         cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(), 
 
3441                                         cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(), 
 
3442                                         cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(), 
 
3443                                         cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(), 
 
3444                                         cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
 
3445                                         cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(), 
 
3446                                         cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
 
3447                                         cenV2User.isOnline(),cenV2User.getChatId(), 
 
3452         public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
 
3453                 List<CentralRole> cenRoleList = new ArrayList<>();
 
3454                         for(CentralV2Role v2CenRole : v2CenRoleList){
 
3455                                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
 
3456                                 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
 
3457                                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
 
3458                                         cenRoleFuncList.add(roleFunc);
 
3460                                 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList);
 
3461                                 cenRoleList.add(role);
 
3467         public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
 
3468                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
3469                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
3470                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
 
3471                 ResponseEntity<String> response = null;
 
3474                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
3475                                                         + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
 
3476                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
 
3477                                         response.getStatusCode().value());
 
3478                 } catch (HttpClientErrorException e) {
 
3479                         logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
 
3480                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
3481                         if (e.getStatusCode() == HttpStatus.NOT_FOUND)
 
3482                                 throw new InvalidApplicationException("Invalid NameSpace");
 
3490         public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
 
3491                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
 
3492                 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
 
3493                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
 
3494                         cenRoleFuncList.add(roleFunc);
 
3496                 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
 
3500         @SuppressWarnings("unchecked")
 
3502         public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
 
3503                 EPApp app = getApp(uebkey).get(0);
 
3504                 final Map<String, String> params = new HashMap<>();
 
3505                 params.put("uebKey", app.getUebKey());
 
3506                 params.put("roleId", String.valueOf(roleId));
 
3507                 List<BulkUploadUserRoles> userRolesList = null;
 
3508                 Integer userRolesAdded = 0;
 
3509                 if (app.getCentralAuth()) {
 
3510                         userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
 
3511                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
 
3512                                 userRolesUpload.setRoleName(modifiedRoleName);
 
3513                                 if(!userRolesUpload.getOrgUserId().equals("su1234")){
 
3514                                         addUserRoleInExternalSystem(userRolesUpload);
 
3519                 return userRolesAdded;
 
3523         public String encodeFunctionCode(String funCode){
 
3524                 String encodedString = funCode;
 
3525                 List<Pattern> encodingList = new ArrayList<>();
 
3526                 encodingList.add(Pattern.compile("/"));
 
3527                 encodingList.add(Pattern.compile("-"));
 
3528                 for (Pattern xssInputPattern : encodingList) {
 
3529                         encodedString = xssInputPattern.matcher(encodedString)
 
3530                                         .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
 
3532                 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
 
3533                 return encodedString;
 
3537         public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
 
3538                 ObjectMapper mapper = new ObjectMapper();
 
3539                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
3541                         ExternalAccessRolePerms extRolePerms;
 
3542                         ExternalAccessPerms extPerms;
 
3543                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction());
 
3544                         String appNameSpace = "";
 
3545                         if(data.getIsGlobalRolePartnerFunc()) {
 
3546                                 appNameSpace =  epAppService.getApp(1l).getNameSpace();
 
3548                                 appNameSpace =  app.getNameSpace();
 
3550                         extRolePerms = new ExternalAccessRolePerms(extPerms,
 
3552                                                         + data.getRoleName().replaceAll(
 
3553                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
 
3555                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
 
3556                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
 
3557                         updateRoleFunctionInExternalSystem(updateRolePerms, entity);
 
3558                 } catch (HttpClientErrorException e) {
 
3559                         logger.error(EELFLoggerDelegate.errorLogger,
 
3560                                         "HttpClientErrorException - Failed to add role function in external central auth system", e);
 
3561                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
 
3563                 } catch (Exception e) {
 
3564                         logger.error(EELFLoggerDelegate.errorLogger,
 
3565                                         "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
 
3571         private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
 
3572                 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
 
3573                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
 
3574                 ResponseEntity<String> addPermResponse = template.exchange(
 
3575                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
 
3576                                 HttpMethod.POST, entity, String.class);
 
3577                 logger.debug(EELFLoggerDelegate.debugLogger,
 
3578                                 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
 
3579                                 addPermResponse.getStatusCode().value(), updateRolePerms);
 
3583         public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
 
3585                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
 
3586                         name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
 
3588                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
3589                 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
 
3590                 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
 
3591                 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
 
3592                 String res = getResponse.getBody();
 
3593                 JSONObject jsonObj = null;
 
3594                 JSONArray extRoles = null;
 
3595                 if (!res.equals("{}")) {
 
3596                         jsonObj = new JSONObject(res);
 
3597                         extRoles = jsonObj.getJSONArray("role");
 
3599                 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
 
3602         @SuppressWarnings("unchecked")
 
3603         private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
 
3604                         String loginId) throws InvalidUserException {
 
3605                 HashMap<String, String> userParams = new HashMap<>();
 
3606                 userParams.put("orgUserId", loginId);
 
3607                 // Get all centralized applications existing user roles from local
 
3608                 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
 
3609                                 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
 
3610                 EPUser user = getUser(loginId).get(0);
 
3611                 // Get all centralized applications roles from local
 
3612                 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
 
3613                 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
 
3614                                 currentUserAppRoles);
 
3615                 // Get all centralized applications + admin role from local
 
3616                 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
 
3617                 if (extRoles != null) {
 
3618                         ExternalAccessUserRoleDetail userRoleDetail = null;
 
3619                         for (int i = 0; i < extRoles.length(); i++) {
 
3620                                 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
 
3621                                                 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
 
3622                                         userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
 
3624                                         userRoleDetailList.add(userRoleDetail);
 
3627                         addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
 
3628                                         centralisedAppsMap);
 
3632         private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
 
3633                         HashMap<String, CentralizedAppRoles> cenAppRolesMap,
 
3634                         HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
 
3635                         HashMap<String, EPApp> centralisedAppsMap) {
 
3636                 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
 
3638                                 // check if user already has role in local
 
3639                                 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
 
3640                                         CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
 
3641                                         if (getCenAppRole != null) {
 
3642                                                 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system  {}",
 
3643                                                                 extUserRoleDetail.toString());
 
3644                                                 EPUserApp userApp = new EPUserApp();
 
3645                                                 EPApp app = new EPApp();
 
3646                                                 app.setId(getCenAppRole.getAppId());
 
3647                                                 EPRole epRole = new EPRole();
 
3648                                                 epRole.setId(getCenAppRole.getRoleId());
 
3649                                                 userApp.setApp(app);
 
3650                                                 userApp.setUserId(user.getId());
 
3651                                                 userApp.setRole(epRole);
 
3652                                                 dataAccessService.saveDomainObject(userApp, null);
 
3653                                                 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system  {}",
 
3654                                                                 extUserRoleDetail.toString());
 
3655                                         } else if (getCenAppRole == null // check if user has app account admin role
 
3656                                                         && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
 
3657                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
 
3658                                                 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
 
3660                                                         logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system  {}",
 
3661                                                                         extUserRoleDetail.toString());
 
3662                                                         EPUserApp userApp = new EPUserApp();
 
3663                                                         EPRole epRole = new EPRole();
 
3664                                                         epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
 
3665                                                         userApp.setApp(app);
 
3666                                                         userApp.setUserId(user.getId());
 
3667                                                         userApp.setRole(epRole);
 
3668                                                         dataAccessService.saveDomainObject(userApp, null);
 
3669                                                         logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system  {}",
 
3670                                                                         extUserRoleDetail.toString());
 
3674                         } catch (Exception e) {
 
3675                                 logger.error(EELFLoggerDelegate.errorLogger,
 
3676                                                 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
 
3677                                                 extUserRoleDetail.toString(), e);
 
3682         @SuppressWarnings("unchecked")
 
3683         private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
 
3684                 List<EPApp> centralizedApps = dataAccessService
 
3685                                 .executeNamedQuery("getCentralizedApps", null, null);
 
3686                 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
 
3687                 for (EPApp cenApp : centralizedApps) {
 
3688                         centralisedAppsMap.put(cenApp.getNameSpace()+ "." +
 
3689                                         PortalConstants.ADMIN_ROLE.replaceAll(
 
3690                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp);
 
3692                 return centralisedAppsMap;
 
3695         private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
 
3696                         List<CentralizedAppRoles> currentUserAppRoles) {
 
3697                 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
 
3698                 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
 
3699                         currentCentralizedUserAppRolesMap.put(
 
3700                                         cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName()
 
3701                                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
 
3704                 return currentCentralizedUserAppRolesMap;
 
3707         @SuppressWarnings("unchecked")
 
3708         private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
 
3709                 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
 
3710                                 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
 
3711                 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
 
3712                 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
 
3714                                         CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName()
 
3715                                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
 
3716                                         CentralizedAppRole);
 
3718                 return cenAppRolesMap;
 
3722         public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
 
3723                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
 
3724                 ResponseEntity<String> getResponse = template
 
3725                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
3726                                                 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
 
3727                 if (getResponse.getStatusCode().value() == 200) {
 
3728                         logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
 
3729                                         getResponse.getBody());
 
3732                         logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
 
3733                         EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());