2  * ================================================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property
 
   6  * ================================================================================
 
   7  * Licensed under the Apache License, Version 2.0 (the "License");
 
   8  * you may not use this file except in compliance with the License.
 
   9  * You may obtain a copy of the License at
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  13  * Unless required by applicable law or agreed to in writing, software
 
  14  * distributed under the License is distributed on an "AS IS" BASIS,
 
  15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  * See the License for the specific language governing permissions and
 
  17  * limitations under the License.
 
  18  * ================================================================================
 
  21 package org.openecomp.portalapp.portal.service;
 
  23 import java.util.ArrayList;
 
  24 import java.util.Arrays;
 
  25 import java.util.Collection;
 
  26 import java.util.Date;
 
  27 import java.util.HashMap;
 
  28 import java.util.HashSet;
 
  29 import java.util.LinkedHashSet;
 
  30 import java.util.List;
 
  33 import java.util.TreeSet;
 
  34 import java.util.stream.Collectors;
 
  36 import javax.servlet.http.HttpServletResponse;
 
  38 import org.apache.commons.lang.StringUtils;
 
  39 import org.apache.cxf.transport.http.HTTPException;
 
  40 import org.hibernate.SQLQuery;
 
  41 import org.hibernate.Session;
 
  42 import org.hibernate.SessionFactory;
 
  43 import org.hibernate.Transaction;
 
  44 import org.json.JSONArray;
 
  45 import org.json.JSONObject;
 
  46 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
 
  47 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser;
 
  48 import org.openecomp.portalapp.portal.domain.EPApp;
 
  49 import org.openecomp.portalapp.portal.domain.EPRole;
 
  50 import org.openecomp.portalapp.portal.domain.EPUser;
 
  51 import org.openecomp.portalapp.portal.domain.EPUserApp;
 
  52 import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles;
 
  53 import org.openecomp.portalapp.portal.domain.EPUserAppRoles;
 
  54 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest;
 
  55 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail;
 
  56 import org.openecomp.portalapp.portal.domain.ExternalSystemAccess;
 
  57 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
 
  58 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
 
  59 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
 
  60 import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
 
  61 import org.openecomp.portalapp.portal.transport.EPUserAppCurrentRoles;
 
  62 import org.openecomp.portalapp.portal.transport.EcompUserAppRoles;
 
  63 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
 
  64 import org.openecomp.portalapp.portal.transport.ExternalAccessUserRoleDetail;
 
  65 import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator;
 
  66 import org.openecomp.portalapp.portal.transport.ExternalRoleDescription;
 
  67 import org.openecomp.portalapp.portal.transport.FieldsValidator;
 
  68 import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
 
  69 import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
 
  70 import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles;
 
  71 import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
 
  72 import org.openecomp.portalapp.portal.transport.RolesInAppForUser;
 
  73 import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
 
  74 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
 
  75 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
 
  76 import org.openecomp.portalapp.portal.utils.PortalConstants;
 
  77 import org.openecomp.portalsdk.core.domain.Role;
 
  78 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
  79 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
 
  80 import org.openecomp.portalsdk.core.service.DataAccessService;
 
  81 import org.openecomp.portalsdk.core.service.RoleService;
 
  82 import org.openecomp.portalsdk.core.util.SystemProperties;
 
  83 import org.springframework.beans.factory.annotation.Autowired;
 
  84 import org.springframework.http.HttpEntity;
 
  85 import org.springframework.http.HttpHeaders;
 
  86 import org.springframework.http.HttpMethod;
 
  87 import org.springframework.http.ResponseEntity;
 
  88 import org.springframework.web.client.RestTemplate;
 
  90 import com.fasterxml.jackson.core.JsonProcessingException;
 
  91 import com.fasterxml.jackson.databind.DeserializationFeature;
 
  92 import com.fasterxml.jackson.databind.ObjectMapper;
 
  95 public class UserRolesCommonServiceImpl  {
 
  97         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
 
  99         private static final Object syncRests = new Object();
 
 102         private DataAccessService dataAccessService;                            
 
 104         private SessionFactory sessionFactory;
 
 106         private SearchService searchService;
 
 108         private EPAppService appsService;
 
 110         private ApplicationsRestClientService applicationsRestClientService;
 
 112         private EPRoleService epRoleService;
 
 114         private RoleService roleService;        
 
 117         private ExternalAccessRolesService externalAccessRolesService;
 
 119         RestTemplate template = new RestTemplate();
 
 124          * @return  HashMap<Long, EcompRole>
 
 126         private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
 
 127                 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
 
 128                 if (ecompRoles != null) {
 
 129                         for (int i = 0; i < ecompRoles.length; i++) {
 
 130                                 if (ecompRoles[i].getId() != null) {
 
 131                                         result.put(ecompRoles[i].getId(), ecompRoles[i]);
 
 142         protected void createLocalUserIfNecessary(String userId) {
 
 143                 if (StringUtils.isEmpty(userId)) {
 
 144                         logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
 
 147                 Session localSession = null;
 
 148                 Transaction transaction = null;
 
 150                         localSession = sessionFactory.openSession();
 
 151                         transaction = localSession.beginTransaction();
 
 152                         @SuppressWarnings("unchecked")
 
 153                         List<EPUser> userList = localSession
 
 154                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
 
 155                         if (userList.size() == 0) {
 
 156                                 EPUser client = searchService.searchUserByUserId(userId);
 
 157                                 if (client == null) {
 
 158                                         String msg = "createLocalUserIfNecessary: cannot create user " + userId
 
 159                                                         + ", because not found in phonebook";
 
 160                                         logger.error(EELFLoggerDelegate.errorLogger, msg);
 
 162                                         client.setLoginId(userId);
 
 163                                         client.setActive(true);
 
 164                                         localSession.save(client);
 
 167                         transaction.commit();
 
 168                 } catch (Exception e) {
 
 169                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 170                         EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
 
 172                         EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
 
 177          * This method return nothing and remove roles before adding any roles for an app
 
 180          * @param localSession
 
 181          * @param userAppRoles
 
 182          * @param newUserAppRolesMap
 
 184         private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
 
 186                 Long userAppRoleId = 0L;
 
 187                 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
 
 188                         userAppRoleId = userRole.getRoleId();
 
 189                 } else { // remote app
 
 190                         userAppRoleId = userRole.getAppRoleId();
 
 193                 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
 
 194                         localSession.delete(userRole);
 
 196                         newUserAppRolesMap.remove(userAppRoleId);
 
 201          * Checks whether the role is inactive
 
 205          *                      if role is inactive, throws exception
 
 207         private void checkIfRoleInactive(EPRole epRole) throws Exception{       
 
 208                 if(!epRole.getActive()){
 
 209                         throw new Exception(epRole.getName()+ " role is unavailable");
 
 215          * @param sessionFactory
 
 218          * @param userAppRoles
 
 219          * @param extRequestValue 
 
 220          *                      set to false if request is from users page otherwise true
 
 223         protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
 
 224                         EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
 
 225                 boolean result = false;
 
 226                 Session localSession = null;
 
 227                 Transaction transaction = null;
 
 228                 String roleActive = null;
 
 229                 final Map<String, String> userAppParams = new HashMap<>();
 
 230                 final Map<String, String> appParams = new HashMap<>();
 
 231                 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
 
 234                         localSession = sessionFactory.openSession();
 
 235                         transaction = localSession.beginTransaction();
 
 236                         @SuppressWarnings("unchecked")
 
 237                         List<EPUser> userList = localSession
 
 238                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
 
 239                         if (userList.size() > 0) {
 
 240                                 EPUser client = userList.get(0);
 
 241                                 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
 
 242                                 @SuppressWarnings("unchecked")
 
 243                                 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
 
 244                                                 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
 
 246                                 if ("DELETE".equals(reqType)) {
 
 247                                         for (EPUserApp userAppRoleList : userRoles) {
 
 248                                                 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
 
 249                                                 userAppParams.put("appId",  String.valueOf(appId));
 
 250                                                 appParams.put("appRoleName", userAppRoleList.getRole().getName());
 
 251                                                 @SuppressWarnings("unchecked")
 
 252                                                 List<EPRole>  rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);        
 
 253                                                 if(rolesList.size() > 0 || !rolesList.isEmpty()){
 
 254                                                 checkIfRoleInactive(rolesList.get(0));
 
 259                                 for (EPUserApp userRole : userRoles) {
 
 260                                         if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
 
 261                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 263                                         else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
 
 264                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 266                                         else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
 
 267                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 270                                 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
 
 271                                 if (newRolesToAdd.size() > 0) {
 
 272                                         EPApp app = (EPApp) localSession.get(EPApp.class, appId);
 
 274                                         HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
 
 275                                         if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
 
 276                                                 String appIdValue = "";
 
 277                                                 if(!extRequestValue){
 
 278                                                         appIdValue = "and id != " +  PortalConstants.SYS_ADMIN_ROLE_ID; 
 
 280                                                 @SuppressWarnings("unchecked")
 
 281                                                 List<EPRole> roles = localSession
 
 282                                                                 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
 
 283                                                 for (EPRole role : roles) {
 
 285                                                         rolesMap.put(role.getId(), role);
 
 287                                         } else { // remote app
 
 288                                                 @SuppressWarnings("unchecked")
 
 289                                                 List<EPRole> roles = localSession
 
 290                                                                 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
 
 291                                                 for (EPRole role : roles) {
 
 292                                                         if (!extRequestValue && app.getCentralAuth()) {
 
 293                                                                 rolesMap.put(role.getId(), role);
 
 295                                                                 rolesMap.put(role.getAppRoleId(), role);
 
 301                                         for (EcompRole userRole : newRolesToAdd) {
 
 302                                                 EPUserApp userApp = new EPUserApp();
 
 303                                                 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
 
 304                                                         role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
 
 305                                                         userApp.setRole(role);
 
 306                                                 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
 
 308                                                 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
 
 312                                                         userApp.setRole(rolesMap.get(userRole.getId()));
 
 315                                                 userApp.setUserId(client.getId());
 
 317                                                 localSession.save(userApp);
 
 318                                                 localSession.flush();
 
 321                                         if (appId == PortalConstants.PORTAL_APP_ID) {
 
 323                                                  * for local app -- hack - always make sure fn_role
 
 324                                                  * table's app_id is null and not 1 for primary app in
 
 325                                                  * this case being ecomp portal app; reason: hibernate
 
 326                                                  * is rightly setting this to 1 while persisting to
 
 327                                                  * fn_role as per the mapping but SDK role management
 
 328                                                  * code expects the app_id to be null as there is no
 
 329                                                  * concept of App_id in SDK
 
 331                                                 localSession.flush();
 
 332                                                 SQLQuery sqlQuery = localSession
 
 333                                                                 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
 
 334                                                 sqlQuery.executeUpdate();
 
 339                         transaction.commit();
 
 341                 } catch (Exception e) {
 
 342                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 343                         EcompPortalUtils.rollbackTransaction(transaction,
 
 344                                         "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e));
 
 345                         if("DELETE".equals(reqType)){
 
 346                                 throw new Exception(e.getMessage());
 
 349                         localSession.close();
 
 350                         if (!result && !"DELETE".equals(reqType)) {
 
 352                                                 "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
 
 358          * Called when getting the list of roles for the user
 
 361          * @param userAppRoles
 
 362          * @return List<RoleInAppForUser> 
 
 364         protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
 
 365                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
 
 367                 Set<Long> userAppRolesMap = new HashSet<Long>();
 
 368                 if (userAppRoles != null) {
 
 369                         for (EcompRole ecompRole : userAppRoles) {
 
 370                                 userAppRolesMap.add(ecompRole.getId());
 
 373                         logger.error(EELFLoggerDelegate.errorLogger,
 
 374                                         "constructRolesInAppForUserGet has received userAppRoles list empty");
 
 377                 if (appRoles != null) {
 
 378                         for (EcompRole ecompRole : appRoles) {
 
 379                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
 
 380                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
 
 381                                 rolesInAppForUser.add(roleForUser);
 
 384                         logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
 
 386                 return rolesInAppForUser;
 
 390          * Called when getting the list of roles for the user
 
 393          * @param userAppRoles
 
 394          * @param extRequestValue 
 
 395          *                      set to false if request is from users page otherwise true
 
 396          * @return List<RoleInAppForUser>
 
 398         protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
 
 399                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
 
 401                 Set<Long> userAppRolesMap = new HashSet<Long>();
 
 402                 if (userAppRoles != null) {
 
 403                         for (EPRole ecompRole : userAppRoles) {
 
 404                                 userAppRolesMap.add(ecompRole.getId());
 
 407                         logger.error(EELFLoggerDelegate.errorLogger,
 
 408                                         "constructRolesInAppForUserGet has received userAppRoles list empty.");
 
 411                 if (appRoles != null) {
 
 412                         for (Role ecompRole : appRoles) {
 
 413                                 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
 
 415                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
 
 416                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
 
 417                                 rolesInAppForUser.add(roleForUser);
 
 420                         logger.error(EELFLoggerDelegate.errorLogger,
 
 421                                         "constructRolesInAppForUser has received appRoles list empty.");
 
 423                 return rolesInAppForUser;
 
 428          * copies of methods in GetAppsWithUserRoleState
 
 430          * @param sessionFactory
 
 435         protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
 
 436                 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
 
 437                 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
 
 438                 boolean result = false;
 
 439                 Session localSession = null;
 
 440                 Transaction transaction = null;
 
 443                         localSession = sessionFactory.openSession();
 
 444                         transaction = localSession.beginTransaction();
 
 445                         // Attention! All roles from remote application supposed to be
 
 447                         @SuppressWarnings("unchecked")
 
 448                         List<EPRole> currentAppRoles = localSession
 
 449                                         .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
 
 450                         List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
 
 451                         for (int i = 0; i < currentAppRoles.size(); i++) {
 
 452                                 EPRole oldAppRole = currentAppRoles.get(i);
 
 453                                 if (oldAppRole.getAppRoleId() != null) {
 
 454                                         EcompRole role = null;
 
 455                                         role = newRolesMap.get(oldAppRole.getAppRoleId());
 
 457                                                 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
 
 458                                                         oldAppRole.setName(role.getName());
 
 459                                                         localSession.update(oldAppRole);
 
 461                                                 newRolesMap.remove(oldAppRole.getAppRoleId());
 
 463                                                 obsoleteRoles.add(oldAppRole);
 
 466                                         obsoleteRoles.add(oldAppRole);
 
 469                         Collection<EcompRole> newRolesToAdd = newRolesMap.values();
 
 470                         for (EcompRole role : newRolesToAdd) {
 
 471                                 logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString());
 
 472                                 EPRole newRole = new EPRole();
 
 473                                 // Attention! All roles from remote application supposed to be
 
 475                                 newRole.setActive(true);
 
 476                                 newRole.setName(role.getName());
 
 477                                 newRole.setAppId(appId);
 
 478                                 newRole.setAppRoleId(role.getId());
 
 479                                 localSession.save(newRole);
 
 481                         if (obsoleteRoles.size() > 0) {
 
 482                                 logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete");
 
 483                                 for (EPRole role : obsoleteRoles) {
 
 484                                         logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString());
 
 485                                         Long roleId = role.getId();
 
 486                                         // delete obsolete roles here
 
 487                                         // Must delete all records with foreign key constraints on
 
 489                                         // fn_user_role, fn_role_composite, fn_role_function,
 
 490                                         // fn_user_pseudo_role, fn_menu_functional_roles.
 
 491                                         // And for fn_menu_functional, if no other roles for that
 
 492                                         // menu item, remove the url.
 
 494                                         // Delete from fn_user_role
 
 495                                         @SuppressWarnings("unchecked")
 
 496                                         List<EPUserApp> userRoles = localSession.createQuery(
 
 497                                                         "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
 
 500                                         logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size());
 
 501                                         for (EPUserApp userRole : userRoles) {
 
 502                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 503                                                                 "about to delete userRole: " + userRole.toString());
 
 504                                                 localSession.delete(userRole);
 
 505                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 506                                                                 "finished deleting userRole: " + userRole.toString());
 
 509                                         // Delete from fn_menu_functional_roles
 
 510                                         @SuppressWarnings("unchecked")
 
 511                                         List<FunctionalMenuRole> funcMenuRoles = localSession
 
 512                                                         .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
 
 514                                         int numMenuRoles = funcMenuRoles.size();
 
 515                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 516                                                         "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
 
 517                                         for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
 
 518                                                 Long menuId = funcMenuRole.menuId;
 
 519                                                 // If this is the only role for this menu item, then the
 
 520                                                 // app and roles will be gone,
 
 521                                                 // so must null out the url too, to be consistent
 
 522                                                 @SuppressWarnings("unchecked")
 
 523                                                 List<FunctionalMenuRole> funcMenuRoles2 = localSession
 
 524                                                                 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
 
 526                                                 int numMenuRoles2 = funcMenuRoles2.size();
 
 527                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 528                                                                 "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
 
 529                                                 localSession.delete(funcMenuRole);
 
 530                                                 if (numMenuRoles2 == 1) {
 
 531                                                         // If this is the only role for this menu item, then
 
 532                                                         // the app and roles will be gone,
 
 533                                                         // so must null out the url too, to be consistent
 
 534                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 535                                                                         "There is exactly 1 menu item for this role, so emptying the url");
 
 536                                                         @SuppressWarnings("unchecked")
 
 537                                                         List<FunctionalMenuItem> funcMenuItems = localSession
 
 539                                                                                         "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
 
 541                                                         if (funcMenuItems.size() > 0) {
 
 542                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
 
 543                                                                 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
 
 544                                                                 funcMenuItem.url = "";
 
 545                                                                 localSession.update(funcMenuItem);
 
 549                                         externalAccessRolesService.deleteRoleDependeciesRecord(localSession, roleId);
 
 550                                         logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString());
 
 551                                         localSession.delete(role);
 
 552                                         logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role");
 
 555                         logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
 
 556                         transaction.commit();
 
 557                         logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
 
 559                 } catch (Exception e) {
 
 560                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 561                         EcompPortalUtils.rollbackTransaction(transaction,
 
 562                                         "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e));
 
 564                         localSession.close();
 
 567                                                 "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'.");
 
 577          * Called when updating the list of roles for the user
 
 581          * @param userRolesInRemoteApp
 
 582          * @return RolesInAppForUser
 
 584         protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
 
 585                         Set<EcompRole> userRolesInRemoteApp) {
 
 586                 RolesInAppForUser result;
 
 587                 result = new RolesInAppForUser();
 
 588                 result.appId = appId;
 
 589                 result.orgUserId = userId;
 
 590                 for (EcompRole role : userRolesInRemoteApp) {
 
 591                         RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
 
 592                         roleInAppForUser.roleId = role.getId();
 
 593                         roleInAppForUser.roleName = role.getName();
 
 594                         roleInAppForUser.isApplied = new Boolean(true);
 
 595                         result.roles.add(roleInAppForUser);
 
 602          * @param roleInAppForUserList
 
 605         protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
 
 606                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 607                         if (roleInAppForUser.isApplied.booleanValue()) {
 
 615          * Builds JSON and posts it to a remote application to update user roles.
 
 617          * @param roleInAppForUserList
 
 619          * @param applicationsRestClientService
 
 622          * @return Set of roles as sent; NOT the response from the app.
 
 623          * @throws JsonProcessingException
 
 624          * @throws HTTPException
 
 626         protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
 
 627                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
 
 628                         throws JsonProcessingException, HTTPException {
 
 629                 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
 
 630                 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
 
 631                 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
 
 632                 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
 
 633                                 String.format("/user/%s/roles", userId));
 
 634                 // TODO: We should add code that verifies that the post operation did
 
 635                 // succeed. Because the SDK may still return 200 OK with an html page
 
 636                 // even when it fails!
 
 637                 return updateUserRolesInEcomp;
 
 642          * @param roleInAppForUserList
 
 643          * @return Set<EcompRole> 
 
 645         protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
 
 646                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
 
 647                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 648                         if (roleInAppForUser.isApplied) {
 
 649                                 EcompRole ecompRole = new EcompRole();
 
 650                                 ecompRole.setId(roleInAppForUser.roleId);
 
 651                                 ecompRole.setName(roleInAppForUser.roleName);
 
 652                                 existingUserRoles.add(ecompRole);
 
 655                 return existingUserRoles;
 
 659          * Constructs user app roles excluding Account Administrator role
 
 661          * @param roleInAppForUserList
 
 663          *            List of roles with Role name, Role Id
 
 665         protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
 
 666                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
 
 667                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 668                         if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
 
 669                                 EcompRole ecompRole = new EcompRole();
 
 670                                 ecompRole.setId(roleInAppForUser.roleId);
 
 671                                 ecompRole.setName(roleInAppForUser.roleName);
 
 672                                 existingUserRoles.add(ecompRole);
 
 675                 return existingUserRoles;
 
 679          * This is for a single app
 
 681          * @param rolesInAppForUser
 
 682          * @param externalSystemRequest  
 
 683          *                      set to false if requests from Users page otherwise true
 
 684          * @return true on success, false otherwise
 
 686         protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
 
 687                 boolean result = false;
 
 688                 String userId = rolesInAppForUser.orgUserId;
 
 689                 Long appId = rolesInAppForUser.appId;
 
 690                 synchronized (syncRests) {
 
 691                         if (rolesInAppForUser != null) {
 
 692                                 createLocalUserIfNecessary(userId);
 
 695                         if (rolesInAppForUser != null) {
 
 696                                 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
 
 697                                 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
 
 698                                         RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
 
 699                                         EcompRole role = new EcompRole();
 
 700                                         role.setId(roleInAppForUser.roleId);
 
 701                                         role.setName(roleInAppForUser.roleName);
 
 702                                         userAppRoles[i] = role;
 
 705                                         syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
 
 707                                 } catch (Exception e) {
 
 708                                         logger.error(EELFLoggerDelegate.errorLogger,
 
 709                                                         "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
 
 710                                         if("DELETE".equals(reqType)){
 
 711                                                 throw new Exception(e.getMessage());
 
 723          * @return UserApplicationRoles
 
 725         protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
 
 726                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
 
 727                 userWithRemoteAppRoles.setAppId(appId);
 
 728                 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
 
 729                 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
 
 730                 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
 
 731                 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
 
 732                 return userWithRemoteAppRoles;
 
 738          * @see org.openecomp.portalapp.portal.service.UserRolesService#
 
 739          * importRolesFromRemoteApplication(java.lang.Long)
 
 741         public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
 
 742                 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
 
 743                 List<EPRole> rolesList = Arrays.asList(appRolesFull);
 
 744                 for (EPRole externalAppRole : rolesList) {
 
 746                         // Try to find an existing extern role for the app in the local
 
 747                         // ecomp DB. If so, then use its id to update the existing external
 
 748                         // application role record.
 
 749                         Long externAppId = externalAppRole.getId();
 
 750                         EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
 
 751                         if (existingAppRole != null) {
 
 752                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 753                                                 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
 
 754                                                                 appId, externAppId));
 
 757                         // persistExternalRoleInEcompDb(externalAppRole, appId,
 
 765          * It adds new user for remote application
 
 767          * @param roleInAppForUserList
 
 768          * @param remoteAppUser
 
 772          * @param searchService
 
 773          * @param applicationsRestClientService
 
 776         private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
 
 777                 EPUser addRemoteUser = null;
 
 778                 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
 
 780                         createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
 
 781                         // If we succeed, we know that the new user was
 
 782                         // persisted on remote app.
 
 783                         addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
 
 784                         if (addRemoteUser == null) {
 
 785                                 logger.error(EELFLoggerDelegate.errorLogger,
 
 786                                                 "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId());
 
 793          * It checks whether the remote user exists or not
 
 794          * if exits returns user object else null
 
 798          * @param applicationsRestClientService
 
 800          * @throws HTTPException
 
 802         private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
 
 803                 EPUser checkRemoteUser = null;
 
 805                         checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
 
 806                 } catch (HTTPException e) {
 
 807                         // Some apps are returning 400 if user is not found.
 
 808                         if (e.getResponseCode() == 400) {
 
 809                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 810                                                 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
 
 812                         } else if(e.getResponseCode() == 404) {
 
 813                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 814                                                 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
 
 817                                 // Other response code, let it come thru.
 
 821                 return checkRemoteUser;
 
 828          * @see org.openecomp.portalapp.portal.service.UserRolesService#
 
 829          * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
 
 830          * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
 
 832         public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
 
 833                 boolean result = false;
 
 834                 boolean epRequestValue = false;
 
 836                 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
 
 837                         userId = newAppRolesForUser.orgUserId.trim();
 
 839                 Long appId = newAppRolesForUser.appId;
 
 840                 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
 
 841                 if (userId.length() > 0) {
 
 842                         ObjectMapper mapper = new ObjectMapper();
 
 843                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
 846                                 EPApp app = appsService.getApp(appId);
 
 847                                 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
 
 849                                 // if centralized app
 
 850                                 if (app.getCentralAuth()) {
 
 851                                         // We should add If user does not exist in remote application
 
 852                                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 853                                                 EPUser remoteAppUser = null;
 
 854                                                 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
 
 856                                                 if (remoteAppUser == null) {
 
 857                                                         addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
 
 858                                                                         applicationsRestClientService);
 
 862                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
 863                                                         applicationsRestClientService, appId, userId);
 
 864                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
 
 865                                                         userRolesInLocalApp);
 
 866                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
 
 867                                         // Apply changes in external Access system
 
 868                                         updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList);
 
 869                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
 
 871                                 // In case if portal is not centralized then follow existing approach
 
 872                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 873                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
 874                                                         applicationsRestClientService, appId, userId);  
 
 875                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
 
 876                                                         userRolesInLocalApp);
 
 877                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
 
 879                                         EPUser remoteAppUser = null;
 
 880                                         if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 882                                                 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
 
 884                                                 if (remoteAppUser == null) {
 
 885                                                         addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
 
 887                                                 if (remoteAppUser != null) {
 
 888                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
 
 889                                                                         applicationsRestClientService, appId, userId);
 
 890                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
 
 891                                                                         userRolesInRemoteApp);
 
 892                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
 
 894                                                         // If no roles remain, request app to set user inactive.
 
 895                                                         if (userRolesInRemoteApp.size() == 0) {
 
 896                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 897                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
 
 899                                                                 remoteAppUser.setActive(false);
 
 900                                                                 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
 
 905                         } catch (Exception e) {
 
 906                                 String message = String.format(
 
 907                                                 "Failed to create user or update user roles for User %s, AppId %s",
 
 908                                                 userId, Long.toString(appId));
 
 909                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
 917         @SuppressWarnings("unchecked")
 
 918         private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser)
 
 921                 //check if user exists 
 
 922                 final Map<String, String> userParams = new HashMap<>();
 
 923                 userParams.put("orgUserIdValue", orgUserId);
 
 924                 List<EPUser> userInfo = checkIfUserExists(userParams);
 
 925                 if (userInfo.size() == 0 || userInfo.isEmpty()) {
 
 926                   createLocalUserIfNecessary(orgUserId);
 
 928                 final Map<String, String> loginIdParams = new HashMap<>();
 
 929                 loginIdParams.put("orgUserIdValue", orgUserId); 
 
 930                 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
 
 932                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
 
 934                                         + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
 
 936                 ObjectMapper mapper = new ObjectMapper();
 
 937                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth()                                         ;
 
 938                 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
 
 939                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
 
 940                 ResponseEntity<String> getResponse = template
 
 941                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 942                                                 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
 
 943                 if(getResponse.getStatusCode().value() == 200){
 
 944                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to external system and received user roles: ", getResponse.getBody());
 
 947                 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
 
 948                 String res = getResponse.getBody();
 
 949                 JSONObject jsonObj = null;
 
 950                 JSONArray extRoles = null;
 
 951                 if (!res.equals("{}")) {
 
 952                         jsonObj = new JSONObject(res);
 
 953                         extRoles = jsonObj.getJSONArray("role");
 
 955                 ExternalAccessUserRoleDetail userRoleDetail = null;
 
 956                 if (extRoles != null) {
 
 957                         for (int i = 0; i < extRoles.length(); i++) {
 
 958                                 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".") && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace()+".admin")
 
 959                                         &&      !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace()+".owner")) {
 
 960                                         ObjectMapper descMapper = new ObjectMapper();
 
 961                                         if(extRoles.getJSONObject(i).has("description")){
 
 962                                                 ExternalRoleDescription desc = descMapper.readValue(
 
 963                                                                 extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
 
 964                                                 userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
 
 966                                                 userRoleDetailList.add(userRoleDetail); 
 
 968                                         userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
 
 970                                         userRoleDetailList.add(userRoleDetail);
 
 976                 for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) {
 
 977                         HttpEntity<String> entity = new HttpEntity<>(headers);
 
 978                         template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
 979                                         + "userRole/" + name + "/" + userRole.getName(), HttpMethod.DELETE, entity, String.class);
 
 981                 final Map<String, RoleInAppForUser> roleInAppUserMap = new HashMap<>();
 
 982                 for(RoleInAppForUser roleInAppUserNew: roleInAppUser){
 
 983                         roleInAppUserMap.put(roleInAppUserNew.getRoleName(), roleInAppUserNew);
 
 985                 final Map<String, Long> params = new HashMap<>();
 
 986                 params.put("appId", app.getId());
 
 987                 params.put("userId", user.getId());
 
 988                 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", params, null);
 
 989                 // Check if incoming request has sys admin or account admin, if exists add in external system
 
 990                         if (!roleInAppUser.isEmpty()) {
 
 991                                 for (EcompUserAppRoles userApp : userAppList) {
 
 992                                         if ((userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
 
 993                                                         || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !roleInAppUserMap.containsKey(userApp.getRoleName())) {
 
 994                                                 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
 
 995                                                 addSpecialRole.setIsApplied(true);
 
 996                                                 addSpecialRole.setRoleId(userApp.getRoleId());
 
 997                                                 addSpecialRole.setRoleName(userApp.getRoleName());
 
 998                                                 roleInAppUser.add(addSpecialRole);
 
1002                 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct().collect(Collectors.toList());
 
1003                 for (RoleInAppForUser addRole : roleInAppUserNonDupls) {
 
1004                         ExternalAccessUser extUser = null;
 
1005                         if ((addRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
 
1006                                         && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1008                                 String extRole = app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ","_");
 
1009                                 HttpEntity<String> entity = new HttpEntity<>(headers);
 
1010                                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
 
1011                                 ResponseEntity<String> getRoleResponse = template.exchange(
 
1012                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"+extRole,
 
1013                                                 HttpMethod.GET, entity, String.class);
 
1014                                 String extAdminRole = app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
 
1015                                 if(getRoleResponse.getBody().equals("{}")){
 
1016                                                 String addDesc = "{\"name\":\"" +extAdminRole+ "\"}";
 
1017                                                 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc,headers);
 
1019                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)  + "role",
 
1020                                                         HttpMethod.POST, roleEntity, String.class);     
 
1022                                 extUser = new ExternalAccessUser(name,
 
1023                                                 app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"));
 
1024                                 } catch(Exception e){
 
1025                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to add admin role for application {} ",app.getId(),e);
 
1029                                 extUser = new ExternalAccessUser(name,
 
1030                                                 app.getNameSpace() + "." + addRole.getRoleName().replaceAll(" ", "_"));
 
1032                         // Assign user role for an application in external access system
 
1033                         String userRole = mapper.writeValueAsString(extUser);
 
1034                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
 
1035                         if (addRole.getIsApplied()) {
 
1036                                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system and adding user role",
 
1037                                                 addRole.getRoleName());
 
1038                                 ResponseEntity<String> addResponse = template.exchange(
 
1039                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
 
1040                                                 HttpMethod.POST, entity, String.class);
 
1041                                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to external system and added user role",
 
1042                                                 getResponse.getBody(), addRole.getRoleName());
 
1043                                 if (addResponse.getStatusCode().value() != 201) {
 
1044                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1045                                                         "Connected to external system unable to save user role", getResponse.getBody(),
 
1046                                                         addRole.getRoleName());
 
1047                                         throw new Exception("Failed to add user role for application");
 
1051                 }catch(Exception e){
 
1052                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user role for application {}", app.getId(),e);
 
1061          * @param applicationsRestClientService
 
1062          * @param searchService
 
1066         protected void createNewUserOnRemoteApp(String userId, EPApp app,
 
1067                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
 
1068                         ObjectMapper mapper, boolean postOpenSource) throws Exception {
 
1071                         EPUser client = searchService.searchUserByUserId(userId);
 
1073                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1075                         if (client == null) {
 
1076                                 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
 
1077                                 logger.error(EELFLoggerDelegate.errorLogger, msg);
 
1078                                 throw new Exception(msg);
 
1081                         client.setLoginId(userId);
 
1082                         client.setActive(true);
 
1084                         String userInString = null;
 
1085                         userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
 
1086                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1087                                         "about to post new client to remote application, users json = " + userInString);
 
1088                         applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
 
1092         @SuppressWarnings("unchecked")
 
1093         protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
 
1094                 final Map<String, Long> epRequestParams = new HashMap<>();
 
1096                         EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
 
1097                         epAppRolesRequestData.setUpdatedDate(new Date());
 
1098                         epAppRolesRequestData.setRequestStatus(updateStatus);
 
1099                         HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
 
1100                         addiotonalUpdateParam.put("userId", userId);
 
1101                         dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
 
1102                         epRequestParams.put("reqId", epUserAppRolesRequest.getId());
 
1103                         List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
 
1104                         epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
 
1105                                         epRequestParams, null);
 
1106                         if (epUserAppRolessDetailList.size() > 0) {
 
1107                                 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
 
1108                                         EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
 
1109                                         epAppRoleDetailData.setReqType(updateStatus);
 
1110                                         epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
 
1111                                         HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
 
1112                                         addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
 
1113                                         dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
 
1116                         logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
 
1118                 } catch (Exception e) {
 
1119                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
 
1123         @SuppressWarnings("unchecked")
 
1124         public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
 
1125                 final Map<String, Long> params = new HashMap<>();
 
1126                 final Map<String, Long> epDetailParams = new HashMap<>();
 
1127                 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
 
1128                 params.put("appId", appId);
 
1129                 params.put("userId", user.getId());
 
1131                         epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
 
1132                                         .executeNamedQuery("userAppRolesRequestList", params, null);
 
1133                         if (epRequestIdVal.size() > 0) {
 
1134                                 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
 
1135                                 epAppRolesRequestData.setUpdatedDate(new Date());
 
1136                                 epAppRolesRequestData.setRequestStatus("O");
 
1137                                 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
 
1138                                 addiotonalUpdateParam.put("userId", user.getId());
 
1139                                 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
 
1140                                 epDetailParams.put("reqId", epAppRolesRequestData.getId());
 
1141                                 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
 
1142                                 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
 
1143                                                 epDetailParams, null);
 
1144                                 if (epUserAppRolesDetailList.size() > 0) {
 
1145                                         for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
 
1146                                                 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
 
1147                                                 epAppRoleDetailData.setReqType("O");
 
1148                                                 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
 
1149                                                 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
 
1150                                                 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
 
1151                                                 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
 
1153                                         logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
 
1157                 } catch (Exception e) {
 
1158                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
 
1163          * Pushes specified user details to the specified remote app.
 
1166          *            OrgUserId identifying user at remote app in REST endpoint path
 
1168          *            User details to be pushed
 
1171          * @param applicationsRestClientService
 
1172          * @throws HTTPException
 
1174         protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
 
1175                         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
 
1177                  getUser(userId, app, applicationsRestClientService);
 
1182          * It returns user details for single org user id
 
1186          *              if user exists it returns list of user details otherwise empty value
 
1188         @SuppressWarnings("unchecked")
 
1189         private List<EPUser> checkIfUserExists(Map<String, String> userParams){ 
 
1190                 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
 
1194          * It checks whether the new user is valid or not otherwise throws exception
 
1199          *                      Checks if user is valid and returns message otherwise throws exception
 
1202         private String validateNewUser(String orgUserId, EPApp app) throws Exception {
 
1203                 EPUser epUser = searchService.searchUserByUserId(orgUserId);
 
1204                 if (epUser == null) {
 
1205                         throw new Exception("User does not exist");
 
1206                 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
 
1207                         throw new Exception("User does not exist");
 
1208                 } else if (app == null) {
 
1209                         throw new Exception("Application does not exist");
 
1211                 return "Saved Successfully";
 
1215          *   Checks if the fields exists or not
 
1218          *                      contains user information
 
1222          *                      throws exception if the field is not valid
 
1224         private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
 
1225                 if (userList.size() == 0 || userList.isEmpty() ) {
 
1226                         throw new Exception("User does not exist");
 
1227                 } else if(app == null) {
 
1228                         throw new Exception("Application does not exist");
 
1229                 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1230                         throw new Exception(app.getMlAppName()+" application is unavailable");
 
1234         @SuppressWarnings("unchecked")
 
1235         public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
 
1236                 boolean result = false;
 
1237                 boolean externalSystemRequest = true;
 
1238                 final Map<String, Long> params = new HashMap<>();
 
1239                 final Map<String, String> userParams = new HashMap<>();
 
1240                 List<EPUser> userInfo = null;
 
1241                 EPUser userId = null;
 
1242                 List<EPUserAppRolesRequest> epRequestId = null;
 
1243                 String orgUserId = "";
 
1244                 String updateStatus = "";
 
1245                 String reqMessage = "";
 
1247                 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
 
1248                         orgUserId = newAppRolesForUser.getLoginId().trim();
 
1250                 String appName = newAppRolesForUser.getApplicationName();
 
1251                 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
 
1252                 if (orgUserId.length() > 0) {
 
1253                         ObjectMapper mapper = new ObjectMapper();
 
1254                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1255                         int epRequestIdSize = 0;
 
1257                                 app = appsService.getAppDetail(appName);
 
1258                                 userParams.put("orgUserIdValue", orgUserId);
 
1259                                 userInfo = checkIfUserExists(userParams);
 
1260                                 reqMessage = "Updated Successfully";
 
1261                                 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
 
1262                                         reqMessage = validateNewUser(orgUserId, app);
 
1264                                 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
 
1265                                         validateExternalRequestFields(userInfo, app);
 
1266                                         userId = userInfo.get(0);
 
1267                                         params.put("appId", app.getId());
 
1268                                         params.put("userId", userId.getId());
 
1269                                         epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
 
1270                                                         .executeNamedQuery("userAppRolesRequestList", params, null);
 
1271                                         epRequestIdSize = epRequestId.size();
 
1273                                 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()){        
 
1274                                 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
 
1275                                 syncAppRoles(sessionFactory, app.getId(), appRoles);
 
1278                                 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
 
1279                                                 app.getId(), app.getMlAppName());
 
1280                                 List<EcompUserAppRoles> userRoleList = null;
 
1282                                 final Map<String, Long> appParams = new HashMap<>();
 
1283                                 appParams.put("userId", userId.getId());
 
1284                                 appParams.put("appId", app.getId());
 
1285                                 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
 
1287                                 boolean checkIfAdminRoleExists = false;
 
1288                                 if (reqType.equals("DELETE")) {
 
1289                                         checkIfAdminRoleExists = userRoleList.stream()
 
1290                                                         .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
 
1292                                         checkIfAdminRoleExists = roleInAppForUserList.stream()
 
1293                                                         .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
 
1295                                 // if Centralized app
 
1296                                 if (app.getCentralAuth()) {
 
1297                                         // We should add If user does not exist in remote application
 
1299                                                 if (!(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && checkIfAdminRoleExists
 
1300                                                                 && (roleInAppForUserList.size() == 1 || reqType.equals("DELETE")))) {
 
1301                                                         EPUser remoteAppUser = null;
 
1302                                                         remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app,
 
1303                                                                         applicationsRestClientService);
 
1304                                                         if (remoteAppUser == null) {
 
1305                                                                 addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService,
 
1306                                                                                 applicationsRestClientService);
 
1307                                                                 reqMessage = "Saved Successfully";
 
1310                                         } catch (Exception e) {
 
1311                                                 reqMessage = e.getMessage();
 
1312                                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to added remote user", e);
 
1313                                                 throw new Exception(reqMessage);
 
1315                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
1316                                                         applicationsRestClientService, app.getId(), orgUserId);
 
1317                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
 
1318                                                         userRolesInLocalApp);
 
1319                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
 
1320                                         // Apply changes in external Access system
 
1321                                         updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList);
 
1322                                         logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", logMessage,
 
1323                                                         newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
 
1324                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
 
1326                                 // If local application is not centralized 
 
1327                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
1328                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
1329                                                         applicationsRestClientService, app.getId(), orgUserId); 
 
1330                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
 
1331                                                         userRolesInLocalApp);
 
1332                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
 
1333                                 } else {// remote app
 
1335                                         if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
 
1336                                         EPUser remoteAppUser = null;
 
1337                                                 remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, applicationsRestClientService);
 
1338                                         if (remoteAppUser == null) {
 
1339                                                 addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService);
 
1340                                                 reqMessage = "Saved Successfully";
 
1342                                                 if (remoteAppUser != null) {
 
1343                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
 
1344                                                                         mapper, applicationsRestClientService, app.getId(), orgUserId);
 
1346                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
 
1347                                                                         app.getId(), userRolesInRemoteApp);
 
1348                                                         logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}",
 
1349                                                                         logMessage, newAppRolesForUser.getApplicationName(),
 
1350                                                                         newAppRolesForUser.getLoginId());
 
1351                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
 
1353                                                         // If no roles remain, request app to set user inactive.
 
1354                                                         /*if (userRolesInRemoteApp.size() == 0) {
 
1355                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1356                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
 
1358                                                                 //TODO Need  to fix the logged in user is not set to inactive
 
1359                                                                 remoteAppUser.setActive(false);
 
1360                                                                 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
 
1364                                                 if(!(reqType.equals("DELETE") && userId == null)){
 
1365                                                         reqMessage = "Saved Successfully";
 
1367                                                 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
 
1369                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
 
1370                                                                 userRolesInRemoteApp);
 
1371                                                 logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}",
 
1372                                                                 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
 
1373                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
 
1377                                                 reqMessage = "Failed to save the user app role(s)";
 
1379                                         if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
 
1381                                                 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
 
1384                         } catch (Exception e) {
 
1385                                 String message = String.format("Failed to create user or update user roles for User %s, AppId %s",
 
1386                                                 orgUserId, appName);
 
1387                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1389                                 reqMessage = e.getMessage();
 
1390                                  if(epRequestIdSize > 0 && !userInfo.isEmpty()){
 
1392                                  applyChangesToAppRolesRequest(app.getId(), userId.getId(),
 
1393                                  updateStatus, epRequestId.get(0));
 
1398                 return new ExternalRequestFieldsValidator(result, reqMessage);
 
1403          * @param roleInAppForUserList
 
1405          * @param applicationsRestClientService
 
1408          * @return  Set<EcompRole>
 
1409          * @throws JsonProcessingException
 
1410          * @throws HTTPException
 
1412         private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
 
1413                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
 
1414                         throws JsonProcessingException, HTTPException {
 
1415                 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
 
1416                 return updatedUserRoles;
 
1420          * It constructs and returns list of user app roles when the external API role approval system calls
 
1423          * @param roleInAppForUserList
 
1425          * @return list of user app roles
 
1427          *                 throws exceptions if role id does not exits 
 
1429         private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
 
1430                         Long appId, String appName) throws Exception {
 
1431                 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
 
1432                 EPRole existingAppRole = null;
 
1433                 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
 
1434                         RoleInAppForUser ecompRole = new RoleInAppForUser();
 
1435                         existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
 
1436                         if (existingAppRole == null) {
 
1437                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
 
1438                                                 roleInAppForUserList);
 
1439                                 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
 
1441                         if (!existingAppRole.getActive()) {
 
1442                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
 
1443                                                 roleInAppForUserList);
 
1444                                 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
 
1446                                 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
 
1447                                 ecompRole.roleName = roleInAppForUser.getRoleName();
 
1448                                 ecompRole.isApplied = true;
 
1449                                 existingUserRoles.add(ecompRole);
 
1452                 return existingUserRoles;
 
1461          * @param applicationsRestClientService
 
1463          * @throws HTTPException
 
1465         protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
 
1466                         throws HTTPException {
 
1468                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
 
1469                         // Map<String,String> params = new HashMap<String,String>();
 
1470                         // params.put("sbcid",userId);
 
1471                         @SuppressWarnings("unchecked")
 
1472                         List<EPUser> userList = (List<EPUser>) dataAccessService
 
1473                                         .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
 
1474                         if (userList != null && !userList.isEmpty())
 
1475                                 return userList.get(0);
 
1481                 return getUser(userId, app, applicationsRestClientService);
 
1484         protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
 
1485                         throws HTTPException {
 
1486                 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId));
 
1490         protected boolean isAppUpgradeVersion(EPApp app){
 
1495         public ExternalSystemAccess getExternalRequestAccess(){
 
1496                 ExternalSystemAccess res = null; 
 
1498                         res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
 
1499                                         Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
 
1500                 } catch (Exception e) {
 
1501                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
 
1509          * @see org.openecomp.portalapp.portal.service.UserRolesService#
 
1510          * getAppRolesForUser(java.lang.Long, java.lang.String)
 
1512         @SuppressWarnings("unchecked")
 
1513         public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
 
1515                 List<RoleInAppForUser> rolesInAppForUser = null;
 
1516                 EPApp app = appsService.getApp(appId);
 
1518                         // for ecomp portal app, no need to make a remote call
 
1519                         if (appId == PortalConstants.PORTAL_APP_ID) {           
 
1521                                 List<Role> roleList = roleService.getAvailableRoles(userId);
 
1522                                 List<Role> activeRoleList = new ArrayList<Role>();
 
1523                                 for(Role role: roleList) {
 
1524                                         if(role.getActive()) {
 
1525                                                 if(role.getId() != 1){ // prevent portal admin from being added
 
1526                                                         activeRoleList.add(role);
 
1527                                                 } else if(extRequestValue){
 
1528                                                         activeRoleList.add(role);
 
1533                                 EPUser localUser  = getUserFromApp(userId, app, applicationsRestClientService);
 
1534                                 // If localUser does not exists return roles
 
1535                                 Set<EPRole> roleSet = null;
 
1536                                 EPRole[] roleSetList = null;
 
1537                                 if(localUser != null){
 
1538                                         roleSet = localUser.getAppEPRoles(app);
 
1539                                         roleSetList = roleSet.toArray(new EPRole[0]);
 
1541                                 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
 
1542                                 return rolesInAppForUser;
 
1545                         EcompRole[] appRoles = null;
 
1546                         List<EcompRole> roles = new ArrayList<>();
 
1547                         if(app.getCentralAuth()){
 
1548                                 List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);;
 
1549                                 for(EPRole role : applicationRoles){
 
1550                                         EcompRole ecompRole = new EcompRole();
 
1551                                         ecompRole.setId(role.getId());
 
1552                                         ecompRole.setName(role.getName());
 
1553                                         roles.add(ecompRole);
 
1555                                 appRoles = roles.toArray(new EcompRole[roles.size()]);
 
1557                                 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
 
1559                         // Test this error case, for generating an internal Ecomp Portal
 
1561                         // EcompRole[] appRoles = null;
 
1562                         // If there is an exception in the rest client api, then null will
 
1564                         if (appRoles != null) {
 
1565                                 if(!app.getCentralAuth()) {
 
1566                                 syncAppRoles(sessionFactory, appId, appRoles);
 
1568                                 EcompRole[] userAppRoles = null;
 
1571                                                 if(app.getCentralAuth()){
 
1572                                                         final Map<String, String> params = new HashMap<>();
 
1573                                                         final Map<String, Long> userParams = new HashMap<>();
 
1574                                                         params.put("orgUserIdValue", userId);
 
1575                                                         List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
 
1576                                                         userParams.put("appId", app.getId());
 
1577                                                         userParams.put("userId", user.get(0).getId());  
 
1578                                                         List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
 
1579                                                                 List<EcompRole> setUserRoles = new ArrayList<>();
 
1580                                                                 for(EPUserAppCurrentRoles role : userAppsRolesList){
 
1581                                                                         EcompRole ecompRole = new EcompRole();
 
1582                                                                         ecompRole.setId(role.getRoleId());
 
1583                                                                         ecompRole.setName(role.getRoleName());
 
1584                                                                         setUserRoles.add(ecompRole);
 
1586                                                                 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
 
1587                                                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
 
1588                                                                 return rolesInAppForUser;
 
1590                                                         userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
 
1591                                                                         String.format("/user/%s/roles", userId));
 
1593                                         } catch (HTTPException e) {
 
1594                                                 // Some apps are returning 400 if user is not found.
 
1595                                                 if (e.getResponseCode() == 400) {
 
1596                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1597                                                                         "getAppRolesForUser caught exception with response code 400; continuing", e);
 
1599                                                         // Other response code, let it come thru.
 
1603                                         if (userAppRoles == null) {
 
1604                                                 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
 
1605                                                         EcompPortalUtils.setExternalAppResponseCode(200);
 
1606                                                         String message = String.format(
 
1607                                                                         "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
 
1608                                                                                         + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
 
1609                                                                                         + "Overriding to 200 until framework SDK returns a useful response.",
 
1610                                                                         Long.toString(appId), userId);
 
1611                                                         logger.warn(EELFLoggerDelegate.applicationLogger, message);
 
1615                                          HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
 
1616                                                 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
 
1617                                                 for (int i = 0; i < userAppRoles.length; i++) {
 
1618                                                         if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
 
1619                                                                 EcompRole role = new EcompRole();
 
1620                                                                 role.setId(userAppRoles[i].getId());
 
1621                                                                 role.setName(userAppRoles[i].getName());
 
1622                                                                 activeRoles.add(role);
 
1625                                                 EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
 
1627                                         // If the remote application isn't down we MUST sync user
 
1628                                         // roles here in case we have this user here!
 
1629                                         syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
 
1630                                 } catch (Exception e) {
 
1631                                         // TODO: we may need to check if user exists, maybe remote
 
1633                                         String message = String.format(
 
1634                                                         "getAppRolesForUser: user %s does not exist in remote application %s", userId,
 
1635                                                         Long.toString(appId));
 
1636                                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1637                                         userAppRoles = new EcompRole[0];
 
1639                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
 
1641                 } catch (Exception e) {
 
1642                         String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
 
1643                                         Long.toString(appId));
 
1644                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1646                 return rolesInAppForUser;
 
1650         private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
 
1651                         ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
 
1652                         throws JsonProcessingException, HTTPException {
 
1653                 boolean result = false;
 
1654                 ObjectMapper mapper = new ObjectMapper();
 
1655                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1656                 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
 
1657                 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
 
1658                 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
 
1662         public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
 
1663                 FieldsValidator fieldsValidator = new FieldsValidator();
 
1664                 final Map<String, Long> params = new HashMap<>();
 
1665                 EPUserAppRoles  appRole= new EPUserAppRoles();
 
1667                         logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
 
1668                         boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
 
1670                         params.put("appId", userAppRolesData.appId);
 
1671                         EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
 
1672                         epAppRolesRequestData.setCreatedDate(new Date());
 
1673                         epAppRolesRequestData.setUpdatedDate(new Date());
 
1674                         epAppRolesRequestData.setUserId(user.getId());
 
1675                         epAppRolesRequestData.setAppId(userAppRolesData.appId);
 
1676                         epAppRolesRequestData.setRequestStatus("P");
 
1677                         List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
 
1678                         Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
 
1679                         dataAccessService.saveDomainObject(epAppRolesRequestData, null);
 
1680                         for (RoleInAppForUser userAppRoles : appRoleIdList) {
 
1681                                 Boolean isAppliedVal = userAppRoles.isApplied;
 
1682                                 params.put("appRoleId", userAppRoles.roleId);                           
 
1684                                         appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
 
1685                                         EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
 
1686                                         epAppRoleDetail.setReqRoleId(appRole.getRoleId());
 
1687                                         epAppRoleDetail.setReqType("P");
 
1688                                         epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
 
1689                                         dataAccessService.saveDomainObject(epAppRoleDetail, null);
 
1692                         epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
 
1693                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
 
1695                 } catch (Exception e) {
 
1696                         logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
 
1697                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
 
1699                 return fieldsValidator;
 
1702         public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {      
 
1703                 Map<String, String> params = new HashMap<>();
 
1704                 params.put("userid", userid.getId().toString());
 
1705                 //params.put("appid", appid);
 
1706                 params.put("appName", appName);
 
1708                 @SuppressWarnings("unchecked")
 
1709                 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
 
1710                                 .executeNamedQuery("userAppCatalogRoles", params, null);
 
1711                 return userAppRoles;    
 
1714         public String updateRemoteUserProfile(String orgUserId, Long appId) {
 
1715                 ObjectMapper mapper = new ObjectMapper();
 
1716                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1717                 EPUser client = searchService.searchUserByUserId(orgUserId);
 
1718                 EPUser newUser = new EPUser();
 
1719                 newUser.setActive(client.getActive());
 
1720                 newUser.setFirstName(client.getFirstName());
 
1721                 newUser.setLastName(client.getLastName());
 
1722                 newUser.setLoginId(client.getLoginId());
 
1723                 newUser.setLoginPwd(client.getLoginPwd());
 
1724                 newUser.setMiddleInitial(client.getMiddleInitial());
 
1725                 newUser.setEmail(client.getEmail());
 
1726                 newUser.setOrgUserId(client.getLoginId());
 
1728                         String userAsString = mapper.writeValueAsString(newUser);
 
1729                         List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
 
1730                         // applicationsRestClientService.post(EPUser.class, appId,
 
1731                         // userAsString, String.format("/user", orgUserId));
 
1732                         for (EPApp eachApp : appList) {
 
1734                                         applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
 
1735                                                         String.format("/user/%s", orgUserId));
 
1736                                 } catch (Exception e) {
 
1737                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
 
1738                                                         + " in remote app. appId = " + eachApp.getId());
 
1741                 } catch (Exception e) {
 
1742                         logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
 
1753          * @see org.openecomp.portalapp.portal.service.UserRolesService#
 
1754          * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
 
1756         public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
 
1757                 // Find the records for this user-app combo, if any
 
1758                 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
 
1759                 @SuppressWarnings("unchecked")
 
1760                 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
 
1761                 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());