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;
 
  35 import javax.servlet.http.HttpServletResponse;
 
  37 import org.apache.commons.lang.StringUtils;
 
  38 import org.apache.cxf.transport.http.HTTPException;
 
  39 import org.hibernate.Query;
 
  40 import org.hibernate.SQLQuery;
 
  41 import org.hibernate.Session;
 
  42 import org.hibernate.SessionFactory;
 
  43 import org.hibernate.Transaction;
 
  44 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
 
  45 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser;
 
  46 import org.openecomp.portalapp.portal.domain.EPApp;
 
  47 import org.openecomp.portalapp.portal.domain.EPRole;
 
  48 import org.openecomp.portalapp.portal.domain.EPUser;
 
  49 import org.openecomp.portalapp.portal.domain.EPUserApp;
 
  50 import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles;
 
  51 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest;
 
  52 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail;
 
  53 import org.openecomp.portalapp.portal.domain.EpUserAppRoles;
 
  54 import org.openecomp.portalapp.portal.domain.ExternalSystemAccess;
 
  55 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
 
  56 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
 
  57 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
 
  58 import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
 
  59 import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator;
 
  60 import org.openecomp.portalapp.portal.transport.FieldsValidator;
 
  61 import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
 
  62 import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
 
  63 import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles;
 
  64 import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
 
  65 import org.openecomp.portalapp.portal.transport.RolesInAppForUser;
 
  66 import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
 
  67 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
 
  68 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
 
  69 import org.openecomp.portalapp.portal.utils.PortalConstants;
 
  70 import org.openecomp.portalsdk.core.domain.Role;
 
  71 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
  72 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
 
  73 import org.openecomp.portalsdk.core.service.DataAccessService;
 
  74 import org.openecomp.portalsdk.core.service.RoleService;
 
  75 import org.openecomp.portalsdk.core.util.SystemProperties;
 
  76 import org.springframework.beans.factory.annotation.Autowired;
 
  78 import com.fasterxml.jackson.core.JsonProcessingException;
 
  79 import com.fasterxml.jackson.databind.DeserializationFeature;
 
  80 import com.fasterxml.jackson.databind.ObjectMapper;
 
  83 public class UserRolesCommonServiceImpl  {
 
  85         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
 
  87         private static final Object syncRests = new Object();
 
  90         private DataAccessService dataAccessService;
 
  92         private SessionFactory sessionFactory;
 
  94         private SearchService searchService;
 
  96         private EPAppService appsService;
 
  98         private ApplicationsRestClientService applicationsRestClientService;
 
 100         private EPRoleService epRoleService;
 
 102         private RoleService roleService;
 
 107          * @return  HashMap<Long, EcompRole>
 
 109         private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
 
 110                 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
 
 111                 if (ecompRoles != null) {
 
 112                         for (int i = 0; i < ecompRoles.length; i++) {
 
 113                                 if (ecompRoles[i].getId() != null) {
 
 114                                         result.put(ecompRoles[i].getId(), ecompRoles[i]);
 
 125         protected void createLocalUserIfNecessary(String userId) {
 
 126                 if (StringUtils.isEmpty(userId)) {
 
 127                         logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
 
 130                 Session localSession = null;
 
 131                 Transaction transaction = null;
 
 133                         localSession = sessionFactory.openSession();
 
 134                         transaction = localSession.beginTransaction();
 
 135                         @SuppressWarnings("unchecked")
 
 136                         List<EPUser> userList = localSession
 
 137                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
 
 138                         if (userList.size() == 0) {
 
 139                                 EPUser client = searchService.searchUserByUserId(userId);
 
 140                                 if (client == null) {
 
 141                                         String msg = "createLocalUserIfNecessary: cannot create user " + userId
 
 142                                                         + ", because not found in phonebook";
 
 143                                         logger.error(EELFLoggerDelegate.errorLogger, msg);
 
 145                                         client.setLoginId(userId);
 
 146                                         client.setActive(true);
 
 147                                         localSession.save(client);
 
 150                         transaction.commit();
 
 151                 } catch (Exception e) {
 
 152                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 153                         EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
 
 155                         EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
 
 160          * This method return nothing and remove roles before adding any roles for an app
 
 163          * @param localSession
 
 164          * @param userAppRoles
 
 165          * @param newUserAppRolesMap
 
 167         private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
 
 169                 Long userAppRoleId = 0L;
 
 170                 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
 
 171                         userAppRoleId = userRole.getRoleId();
 
 172                 } else { // remote app
 
 173                         userAppRoleId = userRole.getAppRoleId();
 
 176                 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
 
 177                         localSession.delete(userRole);
 
 179                         newUserAppRolesMap.remove(userAppRoleId);
 
 184          * Checks whether the role is inactive
 
 188          *                      if role is inactive, throws exception
 
 190         private void checkIfRoleInactive(EPRole epRole) throws Exception{       
 
 191                 if(!epRole.getActive()){
 
 192                         throw new Exception(epRole.getName()+ " role is unavailable");
 
 198          * @param sessionFactory
 
 201          * @param userAppRoles
 
 202          * @param extRequestValue 
 
 203          *                      set to false if request is from users page otherwise true
 
 206         protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
 
 207                         EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
 
 208                 boolean result = false;
 
 209                 Session localSession = null;
 
 210                 Transaction transaction = null;
 
 211                 String roleActive = null;
 
 212                 final Map<String, String> userAppParams = new HashMap<>();
 
 213                 final Map<String, String> appParams = new HashMap<>();
 
 214                 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
 
 217                         localSession = sessionFactory.openSession();
 
 218                         transaction = localSession.beginTransaction();
 
 219                         @SuppressWarnings("unchecked")
 
 220                         List<EPUser> userList = localSession
 
 221                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
 
 222                         if (userList.size() > 0) {
 
 223                                 EPUser client = userList.get(0);
 
 224                                 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
 
 225                                 @SuppressWarnings("unchecked")
 
 226                                 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
 
 227                                                 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
 
 229                                 if ("DELETE".equals(reqType)) {
 
 230                                         for (EPUserApp userAppRoleList : userRoles) {
 
 231                                                 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
 
 232                                                 userAppParams.put("appId",  String.valueOf(appId));
 
 233                                                 appParams.put("appRoleName", userAppRoleList.getRole().getName());
 
 234                                                 @SuppressWarnings("unchecked")
 
 235                                                 List<EPRole>  rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);        
 
 236                                                 if(rolesList.size() > 0 || !rolesList.isEmpty()){
 
 237                                                 checkIfRoleInactive(rolesList.get(0));
 
 242                                 for (EPUserApp userRole : userRoles) {
 
 243                                         if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
 
 244                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 246                                         else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
 
 247                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 249                                         else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
 
 250                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 253                                 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
 
 254                                 if (newRolesToAdd.size() > 0) {
 
 255                                         EPApp app = (EPApp) localSession.get(EPApp.class, appId);
 
 257                                         HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
 
 258                                         if (appId == PortalConstants.PORTAL_APP_ID) { // local app
 
 259                                                 String appIdValue = null;
 
 260                                                 if(!extRequestValue){
 
 261                                                         appIdValue = "and id != " +  PortalConstants.PORTAL_APP_ID; 
 
 265                                                 @SuppressWarnings("unchecked")
 
 266                                                 List<EPRole> roles = localSession
 
 267                                                                 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
 
 268                                                 for (EPRole role : roles) {
 
 270                                                         rolesMap.put(role.getId(), role);
 
 272                                         } else { // remote app
 
 273                                                 @SuppressWarnings("unchecked")
 
 274                                                 List<EPRole> roles = localSession
 
 275                                                                 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
 
 276                                                 for (EPRole role : roles) {
 
 277                                                         rolesMap.put(role.getAppRoleId(), role);
 
 281                                         for (EcompRole userRole : newRolesToAdd) {
 
 282                                                 EPUserApp userApp = new EPUserApp();
 
 283                                                 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
 
 284                                                         role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
 
 285                                                         userApp.setRole(role);
 
 286                                                 } else if (userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue){
 
 289                                                         userApp.setRole(rolesMap.get(userRole.getId()));        
 
 292                                                 userApp.setUserId(client.getId());
 
 294                                                 localSession.save(userApp);
 
 295                                                 localSession.flush();
 
 298                                         if (appId == PortalConstants.PORTAL_APP_ID) {
 
 300                                                  * for local app -- hack - always make sure fn_role
 
 301                                                  * table's app_id is null and not 1 for primary app in
 
 302                                                  * this case being ecomp portal app; reason: hibernate
 
 303                                                  * is rightly setting this to 1 while persisting to
 
 304                                                  * fn_role as per the mapping but SDK role management
 
 305                                                  * code expects the app_id to be null as there is no
 
 306                                                  * concept of App_id in SDK
 
 308                                                 SQLQuery sqlQuery = localSession
 
 309                                                                 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
 
 310                                                 sqlQuery.executeUpdate();
 
 316                         transaction.commit();
 
 318                 } catch (Exception e) {
 
 319                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 320                         EcompPortalUtils.rollbackTransaction(transaction,
 
 321                                         "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e));
 
 322                         if("DELETE".equals(reqType)){
 
 323                                 throw new Exception(e.getMessage());
 
 326                         localSession.close();
 
 327                         if (!result && !"DELETE".equals(reqType)) {
 
 329                                                 "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
 
 335          * Called when getting the list of roles for the user
 
 338          * @param userAppRoles
 
 339          * @return List<RoleInAppForUser> 
 
 341         protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
 
 342                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
 
 344                 Set<Long> userAppRolesMap = new HashSet<Long>();
 
 345                 if (userAppRoles != null) {
 
 346                         for (EcompRole ecompRole : userAppRoles) {
 
 347                                 userAppRolesMap.add(ecompRole.getId());
 
 350                         logger.error(EELFLoggerDelegate.errorLogger,
 
 351                                         "constructRolesInAppForUserGet has received userAppRoles list empty");
 
 354                 if (appRoles != null) {
 
 355                         for (EcompRole ecompRole : appRoles) {
 
 356                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
 
 357                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
 
 358                                 rolesInAppForUser.add(roleForUser);
 
 361                         logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
 
 363                 return rolesInAppForUser;
 
 367          * Called when getting the list of roles for the user
 
 370          * @param userAppRoles
 
 371          * @param extRequestValue 
 
 372          *                      set to false if request is from users page otherwise true
 
 373          * @return List<RoleInAppForUser>
 
 375         protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
 
 376                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
 
 378                 Set<Long> userAppRolesMap = new HashSet<Long>();
 
 379                 if (userAppRoles != null) {
 
 380                         for (EPRole ecompRole : userAppRoles) {
 
 381                                 userAppRolesMap.add(ecompRole.getId());
 
 384                         logger.error(EELFLoggerDelegate.errorLogger,
 
 385                                         "constructRolesInAppForUserGet has received userAppRoles list empty.");
 
 388                 if (appRoles != null) {
 
 389                         for (Role ecompRole : appRoles) {
 
 390                                 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
 
 392                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
 
 393                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
 
 394                                 rolesInAppForUser.add(roleForUser);
 
 397                         logger.error(EELFLoggerDelegate.errorLogger,
 
 398                                         "constructRolesInAppForUser has received appRoles list empty.");
 
 400                 return rolesInAppForUser;
 
 405          * copies of methods in GetAppsWithUserRoleState
 
 407          * @param sessionFactory
 
 412         protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
 
 413                 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
 
 414                 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
 
 415                 boolean result = false;
 
 416                 Session localSession = null;
 
 417                 Transaction transaction = null;
 
 420                         localSession = sessionFactory.openSession();
 
 421                         transaction = localSession.beginTransaction();
 
 422                         // Attention! All roles from remote application supposed to be
 
 424                         @SuppressWarnings("unchecked")
 
 425                         List<EPRole> currentAppRoles = localSession
 
 426                                         .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
 
 427                         List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
 
 428                         for (int i = 0; i < currentAppRoles.size(); i++) {
 
 429                                 EPRole oldAppRole = currentAppRoles.get(i);
 
 430                                 if (oldAppRole.getAppRoleId() != null) {
 
 431                                         EcompRole role = null;
 
 432                                         role = newRolesMap.get(oldAppRole.getAppRoleId());
 
 434                                                 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
 
 435                                                         oldAppRole.setName(role.getName());
 
 436                                                         localSession.update(oldAppRole);
 
 438                                                 newRolesMap.remove(oldAppRole.getAppRoleId());
 
 440                                                 obsoleteRoles.add(oldAppRole);
 
 443                                         obsoleteRoles.add(oldAppRole);
 
 446                         Collection<EcompRole> newRolesToAdd = newRolesMap.values();
 
 447                         for (EcompRole role : newRolesToAdd) {
 
 448                                 logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString());
 
 449                                 EPRole newRole = new EPRole();
 
 450                                 // Attention! All roles from remote application supposed to be
 
 452                                 newRole.setActive(true);
 
 453                                 newRole.setName(role.getName());
 
 454                                 newRole.setAppId(appId);
 
 455                                 newRole.setAppRoleId(role.getId());
 
 456                                 localSession.save(newRole);
 
 458                         if (obsoleteRoles.size() > 0) {
 
 459                                 logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete");
 
 460                                 for (EPRole role : obsoleteRoles) {
 
 461                                         logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString());
 
 462                                         Long roleId = role.getId();
 
 463                                         // delete obsolete roles here
 
 464                                         // Must delete all records with foreign key constraints on
 
 466                                         // fn_user_role, fn_role_composite, fn_role_function,
 
 467                                         // fn_user_pseudo_role, fn_menu_functional_roles.
 
 468                                         // And for fn_menu_functional, if no other roles for that
 
 469                                         // menu item, remove the url.
 
 471                                         // Delete from fn_user_role
 
 472                                         @SuppressWarnings("unchecked")
 
 473                                         List<EPUserApp> userRoles = localSession.createQuery(
 
 474                                                         "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
 
 477                                         logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size());
 
 478                                         for (EPUserApp userRole : userRoles) {
 
 479                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 480                                                                 "about to delete userRole: " + userRole.toString());
 
 481                                                 localSession.delete(userRole);
 
 482                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 483                                                                 "finished deleting userRole: " + userRole.toString());
 
 486                                         // Delete from fn_menu_functional_roles
 
 487                                         @SuppressWarnings("unchecked")
 
 488                                         List<FunctionalMenuRole> funcMenuRoles = localSession
 
 489                                                         .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
 
 491                                         int numMenuRoles = funcMenuRoles.size();
 
 492                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 493                                                         "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
 
 494                                         for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
 
 495                                                 Long menuId = funcMenuRole.menuId;
 
 496                                                 // If this is the only role for this menu item, then the
 
 497                                                 // app and roles will be gone,
 
 498                                                 // so must null out the url too, to be consistent
 
 499                                                 @SuppressWarnings("unchecked")
 
 500                                                 List<FunctionalMenuRole> funcMenuRoles2 = localSession
 
 501                                                                 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
 
 503                                                 int numMenuRoles2 = funcMenuRoles2.size();
 
 504                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 505                                                                 "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
 
 506                                                 localSession.delete(funcMenuRole);
 
 507                                                 if (numMenuRoles2 == 1) {
 
 508                                                         // If this is the only role for this menu item, then
 
 509                                                         // the app and roles will be gone,
 
 510                                                         // so must null out the url too, to be consistent
 
 511                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 512                                                                         "There is exactly 1 menu item for this role, so emptying the url");
 
 513                                                         @SuppressWarnings("unchecked")
 
 514                                                         List<FunctionalMenuItem> funcMenuItems = localSession
 
 516                                                                                         "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
 
 518                                                         if (funcMenuItems.size() > 0) {
 
 519                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
 
 520                                                                 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
 
 521                                                                 funcMenuItem.url = "";
 
 522                                                                 localSession.update(funcMenuItem);
 
 527                                         // Delete from fn_role_function
 
 528                                         String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
 
 529                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
 530                                         Query query = localSession.createSQLQuery(sql);
 
 531                                         query.executeUpdate();
 
 533                                         // Delete from ep_role_notification
 
 534                                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
 
 535                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
 536                                         query = localSession.createSQLQuery(sql);
 
 537                                         query.executeUpdate();
 
 539                                         // Delete from fn_role_composite
 
 540                                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id="
 
 542                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
 543                                         query = localSession.createSQLQuery(sql);
 
 544                                         query.executeUpdate();
 
 546                                         // Delete from fn_user_pseudo_role
 
 547                                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
 
 548                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
 
 549                                         query = localSession.createSQLQuery(sql);
 
 550                                         query.executeUpdate();
 
 552                                         logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString());
 
 553                                         localSession.delete(role);
 
 554                                         logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role");
 
 557                         logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
 
 558                         transaction.commit();
 
 559                         logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
 
 561                 } catch (Exception e) {
 
 562                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 563                         EcompPortalUtils.rollbackTransaction(transaction,
 
 564                                         "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e));
 
 566                         localSession.close();
 
 569                                                 "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'.");
 
 575          * Called when updating the list of roles for the user
 
 579          * @param userRolesInRemoteApp
 
 580          * @return RolesInAppForUser
 
 582         protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
 
 583                         Set<EcompRole> userRolesInRemoteApp) {
 
 584                 RolesInAppForUser result;
 
 585                 result = new RolesInAppForUser();
 
 586                 result.appId = appId;
 
 587                 result.orgUserId = userId;
 
 588                 for (EcompRole role : userRolesInRemoteApp) {
 
 589                         RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
 
 590                         roleInAppForUser.roleId = role.getId();
 
 591                         roleInAppForUser.roleName = role.getName();
 
 592                         roleInAppForUser.isApplied = new Boolean(true);
 
 593                         result.roles.add(roleInAppForUser);
 
 600          * @param roleInAppForUserList
 
 603         protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
 
 604                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 605                         if (roleInAppForUser.isApplied.booleanValue()) {
 
 613          * Builds JSON and posts it to a remote application to update user roles.
 
 615          * @param roleInAppForUserList
 
 617          * @param applicationsRestClientService
 
 620          * @return Set of roles as sent; NOT the response from the app.
 
 621          * @throws JsonProcessingException
 
 622          * @throws HTTPException
 
 624         protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
 
 625                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
 
 626                         throws JsonProcessingException, HTTPException {
 
 627                 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
 
 628                 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
 
 629                 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
 
 630                 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
 
 631                                 String.format("/user/%s/roles", userId));
 
 632                 // TODO: We should add code that verifies that the post operation did
 
 633                 // succeed. Because the SDK may still return 200 OK with an html page
 
 634                 // even when it fails!
 
 635                 return updateUserRolesInEcomp;
 
 640          * @param roleInAppForUserList
 
 641          * @return Set<EcompRole> 
 
 643         protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
 
 644                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
 
 645                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 646                         if (roleInAppForUser.isApplied) {
 
 647                                 EcompRole ecompRole = new EcompRole();
 
 648                                 ecompRole.setId(roleInAppForUser.roleId);
 
 649                                 ecompRole.setName(roleInAppForUser.roleName);
 
 650                                 existingUserRoles.add(ecompRole);
 
 653                 return existingUserRoles;
 
 657          * Constructs user app roles excluding Account Administrator role
 
 659          * @param roleInAppForUserList
 
 661          *            List of roles with Role name, Role Id
 
 663         protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
 
 664                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
 
 665                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 666                         if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
 
 667                                 EcompRole ecompRole = new EcompRole();
 
 668                                 ecompRole.setId(roleInAppForUser.roleId);
 
 669                                 ecompRole.setName(roleInAppForUser.roleName);
 
 670                                 existingUserRoles.add(ecompRole);
 
 673                 return existingUserRoles;
 
 677          * This is for a single app
 
 679          * @param rolesInAppForUser
 
 680          * @param externalSystemRequest  
 
 681          *                      set to false if requests from Users page otherwise true
 
 682          * @return true on success, false otherwise
 
 684         protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
 
 685                 boolean result = false;
 
 686                 String userId = rolesInAppForUser.orgUserId;
 
 687                 Long appId = rolesInAppForUser.appId;
 
 688                 synchronized (syncRests) {
 
 689                         if (rolesInAppForUser != null) {
 
 690                                 createLocalUserIfNecessary(userId);
 
 693                         if (rolesInAppForUser != null) {
 
 694                                 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()];
 
 695                                 for (int i = 0; i < rolesInAppForUser.roles.size(); i++) {
 
 696                                         RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
 
 697                                         EcompRole role = new EcompRole();
 
 698                                         role.setId(roleInAppForUser.roleId);
 
 699                                         role.setName(roleInAppForUser.roleName);
 
 700                                         userAppRoles[i] = role;
 
 703                                         syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
 
 705                                 } catch (Exception e) {
 
 706                                         logger.error(EELFLoggerDelegate.errorLogger,
 
 707                                                         "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
 
 708                                         if("DELETE".equals(reqType)){
 
 709                                                 throw new Exception(e.getMessage());
 
 721          * @return UserApplicationRoles
 
 723         protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
 
 724                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
 
 725                 userWithRemoteAppRoles.setAppId(appId);
 
 726                 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
 
 727                 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
 
 728                 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
 
 729                 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
 
 730                 return userWithRemoteAppRoles;
 
 736          * @see org.openecomp.portalapp.portal.service.UserRolesService#
 
 737          * importRolesFromRemoteApplication(java.lang.Long)
 
 739         public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
 
 740                 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
 
 741                 List<EPRole> rolesList = Arrays.asList(appRolesFull);
 
 742                 for (EPRole externalAppRole : rolesList) {
 
 744                         // Try to find an existing extern role for the app in the local
 
 745                         // ecomp DB. If so, then use its id to update the existing external
 
 746                         // application role record.
 
 747                         Long externAppId = externalAppRole.getId();
 
 748                         EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
 
 749                         if (existingAppRole != null) {
 
 750                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 751                                                 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
 
 752                                                                 appId, externAppId));
 
 755                         // persistExternalRoleInEcompDb(externalAppRole, appId,
 
 765          * @see org.openecomp.portalapp.portal.service.UserRolesService#
 
 766          * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
 
 767          * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
 
 769         public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
 
 770                 boolean result = false;
 
 771                 boolean epRequestValue = false;
 
 773                 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
 
 774                         userId = newAppRolesForUser.orgUserId.trim();
 
 776                 Long appId = newAppRolesForUser.appId;
 
 777                 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
 
 778                 if (userId.length() > 0) {
 
 779                         ObjectMapper mapper = new ObjectMapper();
 
 780                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
 783                                 EPApp app = appsService.getApp(appId);
 
 784                                 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
 
 787                                 if (appId == PortalConstants.PORTAL_APP_ID) {
 
 788                                         // EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
 
 789                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
 790                                                         applicationsRestClientService, appId, userId);
 
 791                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
 
 792                                                         userRolesInLocalApp);
 
 793                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
 
 795                                 } else {// remote app
 
 796                                         EPUser remoteAppUser = null;
 
 798                                                 remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService);
 
 799                                         } catch (HTTPException e) {
 
 800                                                 // Some apps are returning 400 if user is not found.
 
 801                                                 if (e.getResponseCode() == 400) {
 
 802                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 803                                                                         "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
 
 806                                                         // Other response code, let it come thru.
 
 810                                         if (remoteAppUser == null) {
 
 811                                                 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
 
 813                                                         createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
 
 814                                                         // If we succeed, we know that the new user was
 
 815                                                         // persisted on remote app.
 
 816                                                         remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService);
 
 817                                                         if (remoteAppUser == null) {
 
 818                                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
 819                                                                                 "Failed to persist new user: " + userId + " in remote app. appId = " + appId);
 
 824                                         if (remoteAppUser != null) {
 
 825                                                 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
 
 826                                                                 applicationsRestClientService, appId, userId);
 
 827                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
 
 828                                                                 userRolesInRemoteApp);
 
 829                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
 
 831                                                 // If no roles remain, request app to set user inactive.
 
 832                                                 if (userRolesInRemoteApp.size() == 0) {
 
 833                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 834                                                                         "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
 
 836                                                         remoteAppUser.setActive(false);
 
 837                                                         postUserToRemoteApp(userId, user, app, applicationsRestClientService);
 
 841                         } catch (Exception e) {
 
 842                                 String message = String.format(
 
 843                                                 "Failed to create user or update user roles for User %s, AppId %s",
 
 844                                                 userId, Long.toString(appId));
 
 845                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
 857          * @param applicationsRestClientService
 
 858          * @param searchService
 
 862         protected void createNewUserOnRemoteApp(String userId, EPApp app,
 
 863                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
 
 864                         ObjectMapper mapper, boolean postOpenSource) throws Exception {
 
 867                         EPUser client = searchService.searchUserByUserId(userId);
 
 869                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
 871                         if (client == null) {
 
 872                                 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
 
 873                                 logger.error(EELFLoggerDelegate.errorLogger, msg);
 
 874                                 throw new Exception(msg);
 
 877                         client.setLoginId(userId);
 
 878                         client.setActive(true);
 
 880                         String userInString = null;
 
 881                         userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
 
 882                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 883                                         "about to post new client to remote application, users json = " + userInString);
 
 884                         applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
 
 888         @SuppressWarnings("unchecked")
 
 889         protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
 
 890                 final Map<String, Long> epRequestParams = new HashMap<>();
 
 892                         EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
 
 893                         epAppRolesRequestData.setUpdatedDate(new Date());
 
 894                         epAppRolesRequestData.setRequestStatus(updateStatus);
 
 895                         HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
 
 896                         addiotonalUpdateParam.put("userId", userId);
 
 897                         dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
 
 898                         epRequestParams.put("reqId", epUserAppRolesRequest.getId());
 
 899                         List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
 
 900                         epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
 
 901                                         epRequestParams, null);
 
 902                         if (epUserAppRolessDetailList.size() > 0) {
 
 903                                 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
 
 904                                         EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
 
 905                                         epAppRoleDetailData.setReqType(updateStatus);
 
 906                                         epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
 
 907                                         HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
 
 908                                         addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
 
 909                                         dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
 
 912                         logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
 
 914                 } catch (Exception e) {
 
 915                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
 
 919         @SuppressWarnings("unchecked")
 
 920         public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
 
 921                 final Map<String, Long> params = new HashMap<>();
 
 922                 final Map<String, Long> epDetailParams = new HashMap<>();
 
 923                 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
 
 924                 params.put("appId", appId);
 
 925                 params.put("userId", user.getId());
 
 927                         epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
 
 928                                         .executeNamedQuery("userAppRolesRequestList", params, null);
 
 929                         if (epRequestIdVal.size() > 0) {
 
 930                                 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
 
 931                                 epAppRolesRequestData.setUpdatedDate(new Date());
 
 932                                 epAppRolesRequestData.setRequestStatus("O");
 
 933                                 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
 
 934                                 addiotonalUpdateParam.put("userId", user.getId());
 
 935                                 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
 
 936                                 epDetailParams.put("reqId", epAppRolesRequestData.getId());
 
 937                                 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
 
 938                                 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
 
 939                                                 epDetailParams, null);
 
 940                                 if (epUserAppRolesDetailList.size() > 0) {
 
 941                                         for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
 
 942                                                 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
 
 943                                                 epAppRoleDetailData.setReqType("O");
 
 944                                                 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
 
 945                                                 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
 
 946                                                 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
 
 947                                                 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
 
 949                                         logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
 
 953                 } catch (Exception e) {
 
 954                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
 
 959          * Pushes specified user details to the specified remote app.
 
 962          *            OrgUserId identifying user at remote app in REST endpoint path
 
 964          *            User details to be pushed
 
 967          * @param applicationsRestClientService
 
 968          * @throws HTTPException
 
 970         protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
 
 971                         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
 
 973                  getUser(userId, app, applicationsRestClientService);
 
 978          * It returns user details for single org user id
 
 982          *              if user exists it returns list of user details otherwise empty value
 
 984         @SuppressWarnings("unchecked")
 
 985         private List<EPUser> checkIfUserExists(Map<String, String> userParams){ 
 
 986                 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
 
 990          * It checks whether the new user is valid or not otherwise throws exception
 
 995          *                      Checks if user is valid and returns message otherwise throws exception
 
 998         private String validateNewUser(String orgUserId, EPApp app) throws Exception {
 
 999                 EPUser epUser = searchService.searchUserByUserId(orgUserId);
 
1000                 if (epUser == null) {
 
1001                         throw new Exception("User does not exist");
 
1002                 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
 
1003                         throw new Exception("User does not exist");
 
1004                 } else if (app == null) {
 
1005                         throw new Exception("Application does not exist");
 
1007                 return "Saved Successfully";
 
1011          *   Checks if the fields exists or not
 
1014          *                      contains user information
 
1018          *                      throws exception if the field is not valid
 
1020         private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
 
1021                 if (userList.size() == 0 || userList.isEmpty() ) {
 
1022                         throw new Exception("User does not exist");
 
1023                 } else if(app == null) {
 
1024                         throw new Exception("Application does not exist");
 
1025                 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1026                         throw new Exception(app.getMlAppName()+" application is unavailable");
 
1030         @SuppressWarnings("unchecked")
 
1031         public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
 
1032                 boolean result = false;
 
1033                 boolean externalSystemRequest = true;
 
1034                 final Map<String, Long> params = new HashMap<>();
 
1035                 final Map<String, String> userParams = new HashMap<>();
 
1036                 List<EPUser> userInfo = null;
 
1037                 EPUser userId = null;
 
1038                 List<EPUserAppRolesRequest> epRequestId = null;
 
1039                 String orgUserId = "";
 
1040                 String updateStatus = "";
 
1041                 String reqMessage = "";
 
1043                 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
 
1044                         orgUserId = newAppRolesForUser.getLoginId().trim();
 
1046                 String appName = newAppRolesForUser.getApplicationName();
 
1047                 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
 
1048                 if (orgUserId.length() > 0) {
 
1049                         ObjectMapper mapper = new ObjectMapper();
 
1050                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1051                         int epRequestIdSize = 0;
 
1053                                 app = appsService.getAppDetail(appName);
 
1054                                 userParams.put("orgUserIdValue", orgUserId);
 
1055                                 userInfo = checkIfUserExists(userParams);
 
1056                                 reqMessage = "Updated Successfully";
 
1057                                 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
 
1058                                         reqMessage = validateNewUser(orgUserId, app);
 
1060                                 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
 
1061                                         validateExternalRequestFields(userInfo, app);
 
1062                                         userId = userInfo.get(0);
 
1063                                         params.put("appId", app.getId());
 
1064                                         params.put("userId", userId.getId());
 
1065                                         epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
 
1066                                                         .executeNamedQuery("userAppRolesRequestList", params, null);
 
1067                                         epRequestIdSize = epRequestId.size();
 
1069                                 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)){ 
 
1070                                 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
 
1071                                 syncAppRoles(sessionFactory, app.getId(), appRoles);
 
1074                                 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
 
1075                                                 app.getId(), app.getMlAppName());
 
1077                                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
 
1078                                         // EPUser localUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
 
1079                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
1080                                                         applicationsRestClientService, app.getId(), orgUserId);
 
1081                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
 
1082                                                         userRolesInLocalApp);
 
1083                                         logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", 
 
1084                                                         logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
 
1085                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
 
1086                                 } else {// remote app
 
1087                                         EPUser remoteAppUser = null;
 
1089                                                 remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
 
1090                                         } catch (HTTPException e) {
 
1091                                                 // Some apps are returning 400 if user is not found.
 
1092                                                 if (e.getResponseCode() == 400) {
 
1093                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1094                                                                         "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
 
1097                                                         // Other response code, let it come thru.
 
1101                                         if (remoteAppUser == null) {
 
1102                                                 createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper,
 
1103                                                                 isAppUpgradeVersion(app));
 
1104                                                 // If we succeed, we know that the new user was
 
1105                                                 // persisted on remote app.
 
1106                                                 remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
 
1107                                                 if (remoteAppUser == null) {
 
1108                                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to persist new user: " + orgUserId
 
1109                                                                         + " in remote app. appId = " + app.getId());
 
1112                                                 reqMessage = "Saved Successfully";
 
1114                                         if (remoteAppUser != null) {
 
1115                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
 
1116                                                                                         mapper, applicationsRestClientService, app.getId(), orgUserId); 
 
1118                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
 
1119                                                                         app.getId(), userRolesInRemoteApp);
 
1120                                                         logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", 
 
1121                                                                         logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
 
1122                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
 
1123                                                         // If no roles remain, request app to set user inactive.
 
1124                                                         /*if (userRolesInRemoteApp.size() == 0) {
 
1125                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1126                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
 
1128                                                                 //TODO Need  to fix the logged in user is not set to inactive
 
1129                                                                 remoteAppUser.setActive(false);
 
1130                                                                 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
 
1135                                                 reqMessage = "Failed to save the user app role(s)";
 
1137                                         if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
 
1139                                                 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
 
1143                         } catch (Exception e) {
 
1144                                 String message = String.format("Failed to create user or update user roles for User %s, AppId %s",
 
1145                                                 orgUserId, appName);
 
1146                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1148                                 reqMessage = e.getMessage();
 
1149                                  if(epRequestIdSize > 0 && !userInfo.isEmpty()){
 
1151                                  applyChangesToAppRolesRequest(app.getId(), userId.getId(),
 
1152                                  updateStatus, epRequestId.get(0));
 
1157                 return new ExternalRequestFieldsValidator(result, reqMessage);
 
1162          * @param roleInAppForUserList
 
1164          * @param applicationsRestClientService
 
1167          * @return  Set<EcompRole>
 
1168          * @throws JsonProcessingException
 
1169          * @throws HTTPException
 
1171         private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
 
1172                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
 
1173                         throws JsonProcessingException, HTTPException {
 
1174                 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
 
1175                 return updatedUserRoles;
 
1179          * It constructs and returns list of user app roles when the external API role approval system calls
 
1182          * @param roleInAppForUserList
 
1184          * @return list of user app roles
 
1186          *                 throws exceptions if role id does not exits 
 
1188         private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
 
1189                         Long appId, String appName) throws Exception {
 
1190                 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
 
1191                 EPRole existingAppRole = null;
 
1192                 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
 
1193                         RoleInAppForUser ecompRole = new RoleInAppForUser();
 
1194                         existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
 
1195                         if (existingAppRole == null) {
 
1196                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
 
1197                                                 roleInAppForUserList);
 
1198                                 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
 
1200                         if (!existingAppRole.getActive()) {
 
1201                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
 
1202                                                 roleInAppForUserList);
 
1203                                 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
 
1205                                 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
 
1206                                 ecompRole.roleName = roleInAppForUser.getRoleName();
 
1207                                 ecompRole.isApplied = true;
 
1208                                 existingUserRoles.add(ecompRole);
 
1211                 return existingUserRoles;
 
1220          * @param applicationsRestClientService
 
1222          * @throws HTTPException
 
1224         protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
 
1225                         throws HTTPException {
 
1227                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
 
1228                         // Map<String,String> params = new HashMap<String,String>();
 
1229                         // params.put("sbcid",userId);
 
1230                         @SuppressWarnings("unchecked")
 
1231                         List<EPUser> userList = (List<EPUser>) dataAccessService
 
1232                                         .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
 
1233                         if (userList != null && !userList.isEmpty())
 
1234                                 return userList.get(0);
 
1240                 return getUser(userId, app, applicationsRestClientService);
 
1243         protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
 
1244                         throws HTTPException {
 
1245                 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId));
 
1249         protected boolean isAppUpgradeVersion(EPApp app){
 
1254         public ExternalSystemAccess getExternalRequestAccess(){
 
1255                 ExternalSystemAccess res = null; 
 
1257                         res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
 
1258                                         Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
 
1259                 } catch (Exception e) {
 
1260                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
 
1268          * @see org.openecomp.portalapp.portal.service.UserRolesService#
 
1269          * getAppRolesForUser(java.lang.Long, java.lang.String)
 
1271         public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
 
1273                 List<RoleInAppForUser> rolesInAppForUser = null;
 
1274                 List<EPUser> userInfo = null;
 
1277                         // for ecomp portal app, no need to make a remote call
 
1278                         if (appId == PortalConstants.PORTAL_APP_ID) {           
 
1279                                 final Map<String, String> userParams = new HashMap<>();
 
1280                                 userParams.put("orgUserIdValue", userId);
 
1281                                 userInfo =      checkIfUserExists(userParams);
 
1282                                 if(userInfo.size() == 0 || userInfo.isEmpty())
 
1284                                         createLocalUserIfNecessary(userId);
 
1287                                 List<Role> roleList = roleService.getAvailableRoles();
 
1288                                 List<Role> activeRoleList = new ArrayList<Role>();
 
1289                                 for(Role role: roleList) {
 
1290                                         if(role.getActive()) {
 
1291                                                 if(role.getId() != 1){ // prevent portal admin from being added
 
1292                                                         activeRoleList.add(role);
 
1293                                                 } else if(extRequestValue){
 
1294                                                         activeRoleList.add(role);
 
1300                                 EPApp app = appsService.getApp(appId);
 
1301                                 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
 
1302                                 Set<EPRole> roleSet = localUser.getAppEPRoles(app);
 
1303                                 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSet.toArray(new EPRole[0]), extRequestValue);
 
1304                                 return rolesInAppForUser;
 
1307                         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
 
1309                         // Test this error case, for generating an internal Ecomp Portal
 
1311                         // EcompRole[] appRoles = null;
 
1312                         // If there is an exception in the rest client api, then null will
 
1314                         if (appRoles != null) {
 
1315                                 syncAppRoles(sessionFactory, appId, appRoles);
 
1316                                 EcompRole[] userAppRoles = null;
 
1319                                                 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
 
1320                                                                 String.format("/user/%s/roles", userId));
 
1321                                         } catch (HTTPException e) {
 
1322                                                 // Some apps are returning 400 if user is not found.
 
1323                                                 if (e.getResponseCode() == 400) {
 
1324                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1325                                                                         "getAppRolesForUser caught exception with response code 400; continuing", e);
 
1327                                                         // Other response code, let it come thru.
 
1331                                         if (userAppRoles == null) {
 
1332                                                 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
 
1333                                                         EcompPortalUtils.setExternalAppResponseCode(200);
 
1334                                                         String message = String.format(
 
1335                                                                         "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
 
1336                                                                                         + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
 
1337                                                                                         + "Overriding to 200 until framework SDK returns a useful response.",
 
1338                                                                         Long.toString(appId), userId);
 
1339                                                         logger.warn(EELFLoggerDelegate.applicationLogger, message);
 
1343                                          HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
 
1344                                                 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
 
1345                                                 for (int i = 0; i < userAppRoles.length; i++) {
 
1346                                                         if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
 
1347                                                                 EcompRole role = new EcompRole();
 
1348                                                                 role.setId(userAppRoles[i].getId());
 
1349                                                                 role.setName(userAppRoles[i].getName());
 
1350                                                                 activeRoles.add(role);
 
1353                                                 EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
 
1355                                         // If the remote application isn't down we MUST sync user
 
1356                                         // roles here in case we have this user here!
 
1357                                         syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
 
1358                                 } catch (Exception e) {
 
1359                                         // TODO: we may need to check if user exists, maybe remote
 
1361                                         String message = String.format(
 
1362                                                         "getAppRolesForUser: user %s does not exist in remote application %s", userId,
 
1363                                                         Long.toString(appId));
 
1364                                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1365                                         userAppRoles = new EcompRole[0];
 
1367                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
 
1369                 } catch (Exception e) {
 
1370                         String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
 
1371                                         Long.toString(appId));
 
1372                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1374                 return rolesInAppForUser;
 
1378         private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
 
1379                         ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
 
1380                         throws JsonProcessingException, HTTPException {
 
1381                 boolean result = false;
 
1382                 ObjectMapper mapper = new ObjectMapper();
 
1383                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1384                 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
 
1385                 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
 
1386                 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
 
1390         public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
 
1391                 FieldsValidator fieldsValidator = new FieldsValidator();
 
1392                 final Map<String, Long> params = new HashMap<>();
 
1393                 EpUserAppRoles  appRole= new EpUserAppRoles();
 
1395                         logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
 
1396                         boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
 
1398                         params.put("appId", userAppRolesData.appId);
 
1399                         EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
 
1400                         epAppRolesRequestData.setCreatedDate(new Date());
 
1401                         epAppRolesRequestData.setUpdatedDate(new Date());
 
1402                         epAppRolesRequestData.setUserId(user.getId());
 
1403                         epAppRolesRequestData.setAppId(userAppRolesData.appId);
 
1404                         epAppRolesRequestData.setRequestStatus("P");
 
1405                         List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
 
1406                         Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
 
1407                         dataAccessService.saveDomainObject(epAppRolesRequestData, null);
 
1408                         for (RoleInAppForUser userAppRoles : appRoleIdList) {
 
1409                                 Boolean isAppliedVal = userAppRoles.isApplied;
 
1410                                 params.put("appRoleId", userAppRoles.roleId);                           
 
1412                                         appRole = (EpUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
 
1413                                         EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
 
1414                                         epAppRoleDetail.setReqRoleId(appRole.getRoleId());
 
1415                                         epAppRoleDetail.setReqType("P");
 
1416                                         epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
 
1417                                         dataAccessService.saveDomainObject(epAppRoleDetail, null);
 
1420                         epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
 
1421                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
 
1423                 } catch (Exception e) {
 
1424                         logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
 
1425                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
 
1427                 return fieldsValidator;
 
1430         public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {      
 
1431                 Map<String, String> params = new HashMap<>();
 
1432                 params.put("userid", userid.getId().toString());
 
1433                 //params.put("appid", appid);
 
1434                 params.put("appName", appName);
 
1436                 @SuppressWarnings("unchecked")
 
1437                 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
 
1438                                 .executeNamedQuery("userAppCatalogRoles", params, null);
 
1439                 return userAppRoles;    
 
1442         public String updateRemoteUserProfile(String orgUserId, Long appId) {
 
1443                 ObjectMapper mapper = new ObjectMapper();
 
1444                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1445                 EPUser client = searchService.searchUserByUserId(orgUserId);
 
1446                 EPUser newUser = new EPUser();
 
1447                 newUser.setActive(client.getActive());
 
1448                 newUser.setFirstName(client.getFirstName());
 
1449                 newUser.setLastName(client.getLastName());
 
1450                 newUser.setLoginId(client.getLoginId());
 
1451                 newUser.setLoginPwd(client.getLoginPwd());
 
1452                 newUser.setMiddleInitial(client.getMiddleInitial());
 
1453                 newUser.setEmail(client.getEmail());
 
1454                 newUser.setOrgUserId(client.getLoginId());
 
1456                         String userAsString = mapper.writeValueAsString(newUser);
 
1457                         List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
 
1458                         // applicationsRestClientService.post(EPUser.class, appId,
 
1459                         // userAsString, String.format("/user", orgUserId));
 
1460                         for (EPApp eachApp : appList) {
 
1462                                         applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
 
1463                                                         String.format("/user/%s", orgUserId));
 
1464                                 } catch (Exception e) {
 
1465                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
 
1466                                                         + " in remote app. appId = " + eachApp.getId());
 
1469                 } catch (Exception e) {
 
1470                         logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
 
1481          * @see org.openecomp.portalapp.portal.service.UserRolesService#
 
1482          * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
 
1484         public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
 
1485                 // Find the records for this user-app combo, if any
 
1486                 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
 
1487                 @SuppressWarnings("unchecked")
 
1488                 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
 
1489                 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());