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 Session localSession = null;
439 Transaction transaction = null;
442 localSession = sessionFactory.openSession();
443 transaction = localSession.beginTransaction();
444 // Attention! All roles from remote application supposed to be
446 @SuppressWarnings("unchecked")
447 List<EPRole> currentAppRoles = localSession
448 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
449 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
450 for (int i = 0; i < currentAppRoles.size(); i++) {
451 EPRole oldAppRole = currentAppRoles.get(i);
452 if (oldAppRole.getAppRoleId() != null) {
453 EcompRole role = null;
454 role = newRolesMap.get(oldAppRole.getAppRoleId());
456 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
457 oldAppRole.setName(role.getName());
458 localSession.update(oldAppRole);
460 newRolesMap.remove(oldAppRole.getAppRoleId());
462 obsoleteRoles.add(oldAppRole);
465 obsoleteRoles.add(oldAppRole);
468 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
469 if (obsoleteRoles.size() > 0) {
470 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
471 for (EPRole role : obsoleteRoles) {
472 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
473 Long roleId = role.getId();
474 // delete obsolete roles here
475 // Must delete all records with foreign key constraints on
477 // fn_user_role, fn_role_composite, fn_role_function,
478 // fn_user_pseudo_role, fn_menu_functional_roles.
479 // And for fn_menu_functional, if no other roles for that
480 // menu item, remove the url.
482 // Delete from fn_user_role
483 @SuppressWarnings("unchecked")
484 List<EPUserApp> userRoles = localSession.createQuery(
485 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
488 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
489 for (EPUserApp userRole : userRoles) {
490 logger.debug(EELFLoggerDelegate.debugLogger,
491 "syncAppRoles: about to delete userRole: " + userRole.toString());
492 localSession.delete(userRole);
493 logger.debug(EELFLoggerDelegate.debugLogger,
494 "syncAppRoles: finished deleting userRole: " + userRole.toString());
497 // Delete from fn_menu_functional_roles
498 @SuppressWarnings("unchecked")
499 List<FunctionalMenuRole> funcMenuRoles = localSession
500 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
502 int numMenuRoles = funcMenuRoles.size();
503 logger.debug(EELFLoggerDelegate.debugLogger,
504 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
505 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
506 Long menuId = funcMenuRole.menuId;
507 // If this is the only role for this menu item, then the
508 // app and roles will be gone,
509 // so must null out the url too, to be consistent
510 @SuppressWarnings("unchecked")
511 List<FunctionalMenuRole> funcMenuRoles2 = localSession
512 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
514 int numMenuRoles2 = funcMenuRoles2.size();
515 logger.debug(EELFLoggerDelegate.debugLogger,
516 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
517 localSession.delete(funcMenuRole);
518 if (numMenuRoles2 == 1) {
519 // If this is the only role for this menu item, then
520 // the app and roles will be gone,
521 // so must null out the url too, to be consistent
522 logger.debug(EELFLoggerDelegate.debugLogger,
523 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
524 @SuppressWarnings("unchecked")
525 List<FunctionalMenuItem> funcMenuItems = localSession
527 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
529 if (funcMenuItems.size() > 0) {
530 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
531 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
532 funcMenuItem.url = "";
533 localSession.update(funcMenuItem);
537 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId);
538 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
539 localSession.delete(role);
540 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
543 for (EcompRole role : newRolesToAdd) {
544 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
545 EPRole newRole = new EPRole();
546 // Attention! All roles from remote application supposed to be
548 newRole.setActive(true);
549 newRole.setName(role.getName());
550 newRole.setAppId(appId);
551 newRole.setAppRoleId(role.getId());
552 localSession.save(newRole);
554 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
555 transaction.commit();
556 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
557 } catch (Exception e) {
558 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
559 EcompPortalUtils.rollbackTransaction(transaction,
560 "syncAppRoles: Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e));
561 throw new Exception(e);
563 localSession.close();
572 * Called when updating the list of roles for the user
576 * @param userRolesInRemoteApp
577 * @return RolesInAppForUser
579 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
580 Set<EcompRole> userRolesInRemoteApp) {
581 RolesInAppForUser result;
582 result = new RolesInAppForUser();
583 result.appId = appId;
584 result.orgUserId = userId;
585 for (EcompRole role : userRolesInRemoteApp) {
586 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
587 roleInAppForUser.roleId = role.getId();
588 roleInAppForUser.roleName = role.getName();
589 roleInAppForUser.isApplied = new Boolean(true);
590 result.roles.add(roleInAppForUser);
597 * @param roleInAppForUserList
600 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
601 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
602 if (roleInAppForUser.isApplied.booleanValue()) {
610 * Builds JSON and posts it to a remote application to update user roles.
612 * @param roleInAppForUserList
614 * @param applicationsRestClientService
617 * @return Set of roles as sent; NOT the response from the app.
618 * @throws JsonProcessingException
619 * @throws HTTPException
621 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
622 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
623 throws JsonProcessingException, HTTPException {
624 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
625 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
626 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
627 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
628 String.format("/user/%s/roles", userId));
629 // TODO: We should add code that verifies that the post operation did
630 // succeed. Because the SDK may still return 200 OK with an html page
631 // even when it fails!
632 return updateUserRolesInEcomp;
637 * @param roleInAppForUserList
638 * @return Set<EcompRole>
640 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
641 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
642 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
643 if (roleInAppForUser.isApplied) {
644 EcompRole ecompRole = new EcompRole();
645 ecompRole.setId(roleInAppForUser.roleId);
646 ecompRole.setName(roleInAppForUser.roleName);
647 existingUserRoles.add(ecompRole);
650 return existingUserRoles;
654 * Constructs user app roles excluding Account Administrator role
656 * @param roleInAppForUserList
658 * List of roles with Role name, Role Id
660 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
661 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
662 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
663 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
664 EcompRole ecompRole = new EcompRole();
665 ecompRole.setId(roleInAppForUser.roleId);
666 ecompRole.setName(roleInAppForUser.roleName);
667 existingUserRoles.add(ecompRole);
670 return existingUserRoles;
674 * This is for a single app
676 * @param rolesInAppForUser
677 * @param externalSystemRequest
678 * set to false if requests from Users page otherwise true
679 * @return true on success, false otherwise
681 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
682 boolean result = false;
683 String userId = rolesInAppForUser.orgUserId;
684 Long appId = rolesInAppForUser.appId;
685 synchronized (syncRests) {
686 if (rolesInAppForUser != null) {
687 createLocalUserIfNecessary(userId);
690 if (rolesInAppForUser != null) {
691 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
692 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
693 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
694 EcompRole role = new EcompRole();
695 role.setId(roleInAppForUser.roleId);
696 role.setName(roleInAppForUser.roleName);
697 userAppRoles[i] = role;
700 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
702 } catch (Exception e) {
703 logger.error(EELFLoggerDelegate.errorLogger,
704 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
705 if("DELETE".equals(reqType)){
706 throw new Exception(e.getMessage());
718 * @return UserApplicationRoles
720 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
721 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
722 userWithRemoteAppRoles.setAppId(appId);
723 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
724 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
725 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
726 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
727 return userWithRemoteAppRoles;
733 * @see org.openecomp.portalapp.portal.service.UserRolesService#
734 * importRolesFromRemoteApplication(java.lang.Long)
736 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
737 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
738 List<EPRole> rolesList = Arrays.asList(appRolesFull);
739 for (EPRole externalAppRole : rolesList) {
741 // Try to find an existing extern role for the app in the local
742 // ecomp DB. If so, then use its id to update the existing external
743 // application role record.
744 Long externAppId = externalAppRole.getId();
745 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
746 if (existingAppRole != null) {
747 logger.debug(EELFLoggerDelegate.debugLogger,
748 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
749 appId, externAppId));
752 // persistExternalRoleInEcompDb(externalAppRole, appId,
760 * It adds new user for remote application
762 * @param roleInAppForUserList
763 * @param remoteAppUser
767 * @param searchService
768 * @param applicationsRestClientService
772 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
773 EPUser addRemoteUser = null;
774 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
776 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
777 // If we succeed, we know that the new user was
778 // persisted on remote app.
779 addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
780 if (addRemoteUser == null) {
781 logger.error(EELFLoggerDelegate.errorLogger,
782 "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId());
786 return addRemoteUser;
790 * It checks whether the remote user exists or not
791 * if exits returns user object else null
795 * @param applicationsRestClientService
797 * @throws HTTPException
799 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
800 EPUser checkRemoteUser = null;
802 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
803 } catch (HTTPException e) {
804 // Some apps are returning 400 if user is not found.
805 if (e.getResponseCode() == 400) {
806 logger.debug(EELFLoggerDelegate.debugLogger,
807 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
809 } else if(e.getResponseCode() == 404) {
810 logger.debug(EELFLoggerDelegate.debugLogger,
811 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
814 // Other response code, let it come thru.
818 return checkRemoteUser;
825 * @see org.openecomp.portalapp.portal.service.UserRolesService#
826 * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
827 * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
829 public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
830 boolean result = false;
831 boolean epRequestValue = false;
833 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
834 userId = newAppRolesForUser.orgUserId.trim();
836 Long appId = newAppRolesForUser.appId;
837 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
838 if (userId.length() > 0) {
839 ObjectMapper mapper = new ObjectMapper();
840 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
843 EPApp app = appsService.getApp(appId);
844 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
846 // if centralized app
847 if (app.getCentralAuth()) {
848 // We should add If user does not exist in remote application
849 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
850 EPUser remoteAppUser = null;
851 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
853 if (remoteAppUser == null) {
854 addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
855 applicationsRestClientService);
859 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
860 applicationsRestClientService, appId, userId);
861 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
862 userRolesInLocalApp);
863 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
864 // Apply changes in external Access system
865 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, epRequestValue);
866 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
868 // In case if portal is not centralized then follow existing approach
869 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
870 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
871 applicationsRestClientService, appId, userId);
872 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
873 userRolesInLocalApp);
874 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
876 EPUser remoteAppUser = null;
877 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
879 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
881 if (remoteAppUser == null) {
882 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
884 if (remoteAppUser != null) {
885 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
886 applicationsRestClientService, appId, userId);
887 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
888 userRolesInRemoteApp);
889 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
891 // If no roles remain, request app to set user inactive.
892 if (userRolesInRemoteApp.size() == 0) {
893 logger.debug(EELFLoggerDelegate.debugLogger,
894 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
896 remoteAppUser.setActive(false);
897 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
902 } catch (Exception e) {
903 String message = String.format(
904 "Failed to create user or update user roles for User %s, AppId %s",
905 userId, Long.toString(appId));
906 logger.error(EELFLoggerDelegate.errorLogger, message, e);
914 * It adds user roles in External system and also make data consistent in both local and in External System
918 * @param roleInAppUser Contains list of active roles
920 @SuppressWarnings("unchecked")
921 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest)
924 // check if user exists
925 final Map<String, String> userParams = new HashMap<>();
926 userParams.put("orgUserIdValue", orgUserId);
927 List<EPUser> userInfo = checkIfUserExists(userParams);
928 if (userInfo.isEmpty()) {
929 createLocalUserIfNecessary(orgUserId);
932 if (EPCommonSystemProperties
933 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
935 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
937 ObjectMapper mapper = new ObjectMapper();
938 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
939 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
940 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
941 ResponseEntity<String> getResponse = template
942 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
943 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
944 if (getResponse.getStatusCode().value() == 200) {
945 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}",
946 getResponse.getBody());
949 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
950 String res = getResponse.getBody();
951 JSONObject jsonObj = null;
952 JSONArray extRoles = null;
953 if (!res.equals("{}")) {
954 jsonObj = new JSONObject(res);
955 extRoles = jsonObj.getJSONArray("role");
957 ExternalAccessUserRoleDetail userRoleDetail = null;
958 if (extRoles != null) {
959 for (int i = 0; i < extRoles.length(); i++) {
960 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
961 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
962 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
963 ObjectMapper descMapper = new ObjectMapper();
964 if (extRoles.getJSONObject(i).has("description")) {
965 ExternalRoleDescription desc = descMapper.readValue(
966 extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
967 userRoleDetail = new ExternalAccessUserRoleDetail(
968 extRoles.getJSONObject(i).getString("name"), desc);
969 userRoleDetailList.add(userRoleDetail);
971 userRoleDetail = new ExternalAccessUserRoleDetail(
972 extRoles.getJSONObject(i).getString("name"), null);
973 userRoleDetailList.add(userRoleDetail);
979 // If request coming from portal not from external role approval system then we have to check if user already
980 // have account admin or system admin as GUI will not send these roles
981 if (!isPortalRequest) {
982 final Map<String, String> loginIdParams = new HashMap<>();
983 loginIdParams.put("orgUserIdValue", orgUserId);
984 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
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",
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)) {
994 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
995 addSpecialRole.setIsApplied(true);
996 addSpecialRole.setRoleId(userApp.getRoleId());
997 addSpecialRole.setRoleName(userApp.getRoleName());
998 roleInAppUser.add(addSpecialRole);
1003 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1004 .collect(Collectors.toList());
1005 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1006 for (RoleInAppForUser roleInAppUserNew : roleInAppUser) {
1007 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName(), roleInAppUserNew);
1009 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1010 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleDetailList) {
1011 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1013 // Check if roles does not exists in local but still there in External Central Auth System delete them all
1014 for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) {
1015 if (!(currentUserRolesToUpdate
1016 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1).replaceAll("_", " "))
1017 || currentUserRolesToUpdate
1018 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1019 HttpEntity<String> entity = new HttpEntity<>(headers);
1020 logger.debug(EELFLoggerDelegate.debugLogger,
1021 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1023 ResponseEntity<String> deleteResponse = template.exchange(
1024 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1025 + "userRole/" + name + "/" + userRole.getName(),
1026 HttpMethod.DELETE, entity, String.class);
1027 logger.debug(EELFLoggerDelegate.debugLogger,
1028 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1029 userRole, deleteResponse.getBody());
1032 // Check if user roles does not exists in External Central Auth System add them all
1033 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1034 if (!(currentUserRolesInExternalSystem
1035 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_")))) {
1036 ExternalAccessUser extUser = new ExternalAccessUser(name,
1037 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_"));
1038 String formattedUserRole = mapper.writeValueAsString(extUser);
1039 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1040 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system and adding user role",
1041 addUserRole.getRoleName());
1042 ResponseEntity<String> addResponse = template
1043 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1044 + "userRole", HttpMethod.POST, entity, String.class);
1045 logger.debug(EELFLoggerDelegate.debugLogger,
1046 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1047 getResponse.getBody(), addUserRole.getRoleName());
1048 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1049 logger.debug(EELFLoggerDelegate.debugLogger,
1050 "Finished POST operation in external system but unable to save user role", getResponse.getBody(),
1051 addUserRole.getRoleName());
1052 throw new Exception(addResponse.getBody());
1056 } catch (Exception e) {
1057 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1066 * @param applicationsRestClientService
1067 * @param searchService
1071 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1072 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1073 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1076 EPUser client = searchService.searchUserByUserId(userId);
1078 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1080 if (client == null) {
1081 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1082 logger.error(EELFLoggerDelegate.errorLogger, msg);
1083 throw new Exception(msg);
1086 client.setLoginId(userId);
1087 client.setActive(true);
1089 String userInString = null;
1090 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1091 logger.debug(EELFLoggerDelegate.debugLogger,
1092 "about to post new client to remote application, users json = " + userInString);
1093 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1097 @SuppressWarnings("unchecked")
1098 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1099 final Map<String, Long> epRequestParams = new HashMap<>();
1101 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1102 epAppRolesRequestData.setUpdatedDate(new Date());
1103 epAppRolesRequestData.setRequestStatus(updateStatus);
1104 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1105 addiotonalUpdateParam.put("userId", userId);
1106 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1107 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1108 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1109 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1110 epRequestParams, null);
1111 if (epUserAppRolessDetailList.size() > 0) {
1112 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1113 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1114 epAppRoleDetailData.setReqType(updateStatus);
1115 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1116 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1117 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1118 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1121 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1123 } catch (Exception e) {
1124 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1128 @SuppressWarnings("unchecked")
1129 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1130 final Map<String, Long> params = new HashMap<>();
1131 final Map<String, Long> epDetailParams = new HashMap<>();
1132 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1133 params.put("appId", appId);
1134 params.put("userId", user.getId());
1136 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1137 .executeNamedQuery("userAppRolesRequestList", params, null);
1138 if (epRequestIdVal.size() > 0) {
1139 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1140 epAppRolesRequestData.setUpdatedDate(new Date());
1141 epAppRolesRequestData.setRequestStatus("O");
1142 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1143 addiotonalUpdateParam.put("userId", user.getId());
1144 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1145 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1146 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1147 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1148 epDetailParams, null);
1149 if (epUserAppRolesDetailList.size() > 0) {
1150 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1151 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1152 epAppRoleDetailData.setReqType("O");
1153 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1154 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1155 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1156 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1158 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1162 } catch (Exception e) {
1163 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1168 * Pushes specified user details to the specified remote app.
1171 * OrgUserId identifying user at remote app in REST endpoint path
1173 * User details to be pushed
1176 * @param applicationsRestClientService
1177 * @throws HTTPException
1179 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1180 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1182 getUser(userId, app, applicationsRestClientService);
1187 * It returns user details for single org user id
1191 * if user exists it returns list of user details otherwise empty value
1193 @SuppressWarnings("unchecked")
1194 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1195 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1199 * It checks whether the new user is valid or not otherwise throws exception
1204 * Checks if user is valid and returns message otherwise throws exception
1207 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1208 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1209 if (epUser == null) {
1210 throw new Exception("User does not exist");
1211 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1212 throw new Exception("User does not exist");
1213 } else if (app == null) {
1214 throw new Exception("Application does not exist");
1216 return "Saved Successfully";
1220 * Checks if the fields exists or not
1223 * contains user information
1227 * throws exception if the field is not valid
1229 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1230 if (userList.size() == 0 || userList.isEmpty() ) {
1231 throw new Exception("User does not exist");
1232 } else if(app == null) {
1233 throw new Exception("Application does not exist");
1234 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1235 throw new Exception(app.getMlAppName()+" application is unavailable");
1239 @SuppressWarnings("unchecked")
1240 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1241 boolean result = false;
1242 boolean externalSystemRequest = true;
1243 final Map<String, Long> params = new HashMap<>();
1244 final Map<String, String> userParams = new HashMap<>();
1245 List<EPUser> userInfo = null;
1246 EPUser userId = null;
1247 List<EPUserAppRolesRequest> epRequestId = null;
1248 String orgUserId = "";
1249 String updateStatus = "";
1250 String reqMessage = "";
1252 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1253 orgUserId = newAppRolesForUser.getLoginId().trim();
1255 String appName = newAppRolesForUser.getApplicationName();
1256 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1257 if (orgUserId.length() > 0) {
1258 ObjectMapper mapper = new ObjectMapper();
1259 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1260 int epRequestIdSize = 0;
1262 app = appsService.getAppDetail(appName);
1263 userParams.put("orgUserIdValue", orgUserId);
1264 userInfo = checkIfUserExists(userParams);
1265 reqMessage = "Updated Successfully";
1266 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1267 reqMessage = validateNewUser(orgUserId, app);
1269 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1270 validateExternalRequestFields(userInfo, app);
1271 userId = userInfo.get(0);
1272 params.put("appId", app.getId());
1273 params.put("userId", userId.getId());
1274 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1275 .executeNamedQuery("userAppRolesRequestList", params, null);
1276 epRequestIdSize = epRequestId.size();
1279 //If Non-Centralized app make sure you sync app roles before assigning to user
1280 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()){
1281 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1282 syncAppRoles(sessionFactory, app.getId(), appRoles);
1284 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1285 app.getId(), app.getMlAppName());
1286 List<EcompUserAppRoles> userRoleList = null;
1287 if(!userInfo.isEmpty()){
1288 final Map<String, Long> appParams = new HashMap<>();
1289 appParams.put("userId", userId.getId());
1290 appParams.put("appId", app.getId());
1291 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1293 // Check if list contains just account admin role
1294 boolean checkIfAdminRoleExists = false;
1295 if (reqType.equals("DELETE")) {
1296 checkIfAdminRoleExists = userRoleList.stream()
1297 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1299 checkIfAdminRoleExists = roleInAppForUserList.stream()
1300 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1302 // if Centralized app
1303 if (app.getCentralAuth()) {
1304 // We should add If user does not exist in remote application
1306 // If adding just account admin role dont make remote application user call
1307 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists
1308 && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) {
1309 EPUser remoteAppUser = null;
1310 remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app,
1311 applicationsRestClientService);
1312 if (remoteAppUser == null) {
1313 addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService,
1314 applicationsRestClientService);
1315 reqMessage = "Saved Successfully";
1318 } catch (Exception e) {
1319 reqMessage = e.getMessage();
1320 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1321 throw new Exception(reqMessage);
1323 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1324 applicationsRestClientService, app.getId(), orgUserId);
1325 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1326 userRolesInLocalApp);
1327 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1328 // Apply changes in external Access system
1329 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
1330 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1331 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1332 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1334 // If local application is not centralized
1335 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1336 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1337 applicationsRestClientService, app.getId(), orgUserId);
1338 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1339 userRolesInLocalApp);
1340 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1341 } else {// remote app
1342 // If adding just account admin role don't do remote application user call
1343 if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
1344 EPUser remoteAppUser = null;
1345 remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, applicationsRestClientService);
1346 if (remoteAppUser == null) {
1347 remoteAppUser = addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService);
1348 reqMessage = "Saved Successfully";
1350 if (remoteAppUser != null) {
1351 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1352 mapper, applicationsRestClientService, app.getId(), orgUserId);
1354 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1355 app.getId(), userRolesInRemoteApp);
1356 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1357 logMessage, newAppRolesForUser.getApplicationName(),
1358 newAppRolesForUser.getLoginId());
1359 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1361 // If no roles remain, request app to set user inactive.
1362 /*if (userRolesInRemoteApp.size() == 0) {
1363 logger.debug(EELFLoggerDelegate.debugLogger,
1364 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1366 //TODO Need to fix the logged in user is not set to inactive
1367 remoteAppUser.setActive(false);
1368 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
1372 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1373 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1374 reqMessage = "Saved Successfully";
1376 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1378 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1379 userRolesInRemoteApp);
1380 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1381 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1382 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1386 reqMessage = "Failed to save the user app role(s)";
1388 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1390 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1393 } catch (Exception e) {
1394 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1395 orgUserId, appName);
1396 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1398 reqMessage = e.getMessage();
1399 if(epRequestIdSize > 0 && !userInfo.isEmpty()){
1401 applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1402 updateStatus, epRequestId.get(0));
1407 return new ExternalRequestFieldsValidator(result, reqMessage);
1412 * @param roleInAppForUserList
1414 * @param applicationsRestClientService
1417 * @return Set<EcompRole>
1418 * @throws JsonProcessingException
1419 * @throws HTTPException
1421 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1422 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1423 throws JsonProcessingException, HTTPException {
1424 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1425 return updatedUserRoles;
1429 * It constructs and returns list of user app roles when the external API role approval system calls
1432 * @param roleInAppForUserList
1434 * @return list of user app roles
1436 * throws exceptions if role id does not exits
1438 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1439 Long appId, String appName) throws Exception {
1440 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1441 EPRole existingAppRole = null;
1442 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1443 RoleInAppForUser ecompRole = new RoleInAppForUser();
1444 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1445 if (existingAppRole == null) {
1446 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1447 roleInAppForUserList);
1448 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1450 if (!existingAppRole.getActive()) {
1451 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1452 roleInAppForUserList);
1453 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1455 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1456 ecompRole.roleName = roleInAppForUser.getRoleName();
1457 ecompRole.isApplied = true;
1458 existingUserRoles.add(ecompRole);
1461 return existingUserRoles;
1470 * @param applicationsRestClientService
1472 * @throws HTTPException
1474 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1475 throws HTTPException {
1477 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1478 // Map<String,String> params = new HashMap<String,String>();
1479 // params.put("sbcid",userId);
1480 @SuppressWarnings("unchecked")
1481 List<EPUser> userList = (List<EPUser>) dataAccessService
1482 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1483 if (userList != null && !userList.isEmpty())
1484 return userList.get(0);
1490 return getUser(userId, app, applicationsRestClientService);
1493 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1494 throws HTTPException {
1495 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId));
1499 protected boolean isAppUpgradeVersion(EPApp app){
1504 public ExternalSystemAccess getExternalRequestAccess(){
1505 ExternalSystemAccess res = null;
1507 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1508 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1509 } catch (Exception e) {
1510 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1518 * @see org.openecomp.portalapp.portal.service.UserRolesService#
1519 * getAppRolesForUser(java.lang.Long, java.lang.String)
1521 @SuppressWarnings("unchecked")
1522 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1524 List<RoleInAppForUser> rolesInAppForUser = null;
1525 EPApp app = appsService.getApp(appId);
1527 // for ecomp portal app, no need to make a remote call
1528 if (appId == PortalConstants.PORTAL_APP_ID) {
1530 List<Role> roleList = roleService.getAvailableRoles(userId);
1531 List<Role> activeRoleList = new ArrayList<Role>();
1532 for(Role role: roleList) {
1533 if(role.getActive()) {
1534 if(role.getId() != 1){ // prevent portal admin from being added
1535 activeRoleList.add(role);
1536 } else if(extRequestValue){
1537 activeRoleList.add(role);
1542 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1543 // If localUser does not exists return roles
1544 Set<EPRole> roleSet = null;
1545 EPRole[] roleSetList = null;
1546 if(localUser != null){
1547 roleSet = localUser.getAppEPRoles(app);
1548 roleSetList = roleSet.toArray(new EPRole[0]);
1550 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1551 return rolesInAppForUser;
1554 EcompRole[] appRoles = null;
1555 List<EcompRole> roles = new ArrayList<>();
1556 if(app.getCentralAuth()){
1557 //Sync application roles from External Access System
1558 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
1559 List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);;
1560 for(EPRole role : applicationRoles){
1561 EcompRole ecompRole = new EcompRole();
1562 ecompRole.setId(role.getId());
1563 ecompRole.setName(role.getName());
1564 roles.add(ecompRole);
1566 appRoles = roles.toArray(new EcompRole[roles.size()]);
1568 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1570 // Test this error case, for generating an internal Ecomp Portal
1572 // EcompRole[] appRoles = null;
1573 // If there is an exception in the rest client api, then null will
1575 if (appRoles != null) {
1576 if(!app.getCentralAuth()) {
1577 syncAppRoles(sessionFactory, appId, appRoles);
1579 EcompRole[] userAppRoles = null;
1582 if(app.getCentralAuth()){
1583 final Map<String, String> params = new HashMap<>();
1584 final Map<String, Long> userParams = new HashMap<>();
1585 params.put("orgUserIdValue", userId);
1586 List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1587 userParams.put("appId", app.getId());
1588 userParams.put("userId", user.get(0).getId());
1589 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1590 List<EcompRole> setUserRoles = new ArrayList<>();
1591 for(EPUserAppCurrentRoles role : userAppsRolesList){
1592 EcompRole ecompRole = new EcompRole();
1593 ecompRole.setId(role.getRoleId());
1594 ecompRole.setName(role.getRoleName());
1595 setUserRoles.add(ecompRole);
1597 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1598 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1599 return rolesInAppForUser;
1601 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1602 String.format("/user/%s/roles", userId));
1604 } catch (HTTPException e) {
1605 // Some apps are returning 400 if user is not found.
1606 if (e.getResponseCode() == 400) {
1607 logger.debug(EELFLoggerDelegate.debugLogger,
1608 "getAppRolesForUser caught exception with response code 400; continuing", e);
1610 // Other response code, let it come thru.
1614 if (userAppRoles == null) {
1615 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1616 EcompPortalUtils.setExternalAppResponseCode(200);
1617 String message = String.format(
1618 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1619 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1620 + "Overriding to 200 until framework SDK returns a useful response.",
1621 Long.toString(appId), userId);
1622 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1626 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1627 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1628 for (int i = 0; i < userAppRoles.length; i++) {
1629 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1630 EcompRole role = new EcompRole();
1631 role.setId(userAppRoles[i].getId());
1632 role.setName(userAppRoles[i].getName());
1633 activeRoles.add(role);
1636 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1638 // If the remote application isn't down we MUST sync user
1639 // roles here in case we have this user here!
1640 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1641 } catch (Exception e) {
1642 // TODO: we may need to check if user exists, maybe remote
1644 String message = String.format(
1645 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1646 Long.toString(appId));
1647 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1648 userAppRoles = new EcompRole[0];
1650 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1652 } catch (Exception e) {
1653 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1654 Long.toString(appId));
1655 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1657 return rolesInAppForUser;
1661 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1662 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1663 throws JsonProcessingException, HTTPException {
1664 boolean result = false;
1665 ObjectMapper mapper = new ObjectMapper();
1666 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1667 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1668 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1669 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1673 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1674 FieldsValidator fieldsValidator = new FieldsValidator();
1675 final Map<String, Long> params = new HashMap<>();
1676 EPUserAppRoles appRole= new EPUserAppRoles();
1678 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1679 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1681 params.put("appId", userAppRolesData.appId);
1682 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1683 epAppRolesRequestData.setCreatedDate(new Date());
1684 epAppRolesRequestData.setUpdatedDate(new Date());
1685 epAppRolesRequestData.setUserId(user.getId());
1686 epAppRolesRequestData.setAppId(userAppRolesData.appId);
1687 epAppRolesRequestData.setRequestStatus("P");
1688 List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1689 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1690 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1691 for (RoleInAppForUser userAppRoles : appRoleIdList) {
1692 Boolean isAppliedVal = userAppRoles.isApplied;
1693 params.put("appRoleId", userAppRoles.roleId);
1695 appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
1696 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1697 epAppRoleDetail.setReqRoleId(appRole.getRoleId());
1698 epAppRoleDetail.setReqType("P");
1699 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1700 dataAccessService.saveDomainObject(epAppRoleDetail, null);
1703 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1704 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1706 } catch (Exception e) {
1707 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1708 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1710 return fieldsValidator;
1713 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
1714 Map<String, String> params = new HashMap<>();
1715 params.put("userid", userid.getId().toString());
1716 //params.put("appid", appid);
1717 params.put("appName", appName);
1719 @SuppressWarnings("unchecked")
1720 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1721 .executeNamedQuery("userAppCatalogRoles", params, null);
1722 return userAppRoles;
1725 public String updateRemoteUserProfile(String orgUserId, Long appId) {
1726 ObjectMapper mapper = new ObjectMapper();
1727 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1728 EPUser client = searchService.searchUserByUserId(orgUserId);
1729 EPUser newUser = new EPUser();
1730 newUser.setActive(client.getActive());
1731 newUser.setFirstName(client.getFirstName());
1732 newUser.setLastName(client.getLastName());
1733 newUser.setLoginId(client.getLoginId());
1734 newUser.setLoginPwd(client.getLoginPwd());
1735 newUser.setMiddleInitial(client.getMiddleInitial());
1736 newUser.setEmail(client.getEmail());
1737 newUser.setOrgUserId(client.getLoginId());
1739 String userAsString = mapper.writeValueAsString(newUser);
1740 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1741 // applicationsRestClientService.post(EPUser.class, appId,
1742 // userAsString, String.format("/user", orgUserId));
1743 for (EPApp eachApp : appList) {
1745 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1746 String.format("/user/%s", orgUserId));
1747 } catch (Exception e) {
1748 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1749 + " in remote app. appId = " + eachApp.getId());
1752 } catch (Exception e) {
1753 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1764 * @see org.openecomp.portalapp.portal.service.UserRolesService#
1765 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1767 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1768 // Find the records for this user-app combo, if any
1769 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1770 @SuppressWarnings("unchecked")
1771 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1772 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());