[PORTAL-20,PORTAL-23,PORTAL-32] Repair defects
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / UserRolesCommonServiceImpl.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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  * ================================================================================
19  */
20
21 package org.openecomp.portalapp.portal.service;
22
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;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.TreeSet;
34
35 import javax.servlet.http.HttpServletResponse;
36
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;
77
78 import com.fasterxml.jackson.core.JsonProcessingException;
79 import com.fasterxml.jackson.databind.DeserializationFeature;
80 import com.fasterxml.jackson.databind.ObjectMapper;
81
82 @EPMetricsLog
83 public class UserRolesCommonServiceImpl  {
84
85         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
86
87         private static final Object syncRests = new Object();
88         
89         @Autowired
90         private DataAccessService dataAccessService;
91         @Autowired
92         private SessionFactory sessionFactory;
93         @Autowired
94         private SearchService searchService;
95         @Autowired
96         private EPAppService appsService;
97         @Autowired
98         private ApplicationsRestClientService applicationsRestClientService;
99         @Autowired
100         private EPRoleService epRoleService;
101         @Autowired
102         private RoleService roleService;
103         
104         /**
105          * 
106          * @param ecompRoles
107          * @return  HashMap<Long, EcompRole>
108          */
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]);
115                                 }
116                         }
117                 }
118                 return result;
119         }
120         
121         /**
122          * 
123          * @param userId
124          */
125         protected void createLocalUserIfNecessary(String userId) {
126                 if (StringUtils.isEmpty(userId)) {
127                         logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
128                         return;
129                 }
130                 Session localSession = null;
131                 Transaction transaction = null;
132                 try {
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);
144                                 } else {
145                                         client.setLoginId(userId);
146                                         client.setActive(true);
147                                         localSession.save(client);
148                                 }
149                         }
150                         transaction.commit();
151                 } catch (Exception e) {
152                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
153                         EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
154                 } finally {
155                         EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
156                 }
157         }
158         
159         /**
160          * This method return nothing and remove roles before adding any roles for an app
161          * @param userRole
162          * @param appId
163          * @param localSession
164          * @param userAppRoles
165          * @param newUserAppRolesMap
166          */
167         private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
168
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();
174                 }
175
176                 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
177                         localSession.delete(userRole);
178                 } else {
179                         newUserAppRolesMap.remove(userAppRoleId);
180                 }
181         }
182         
183         /**
184          * Checks whether the role is inactive
185          *  
186          * @param epRole
187          * @throws Exception
188          *                      if role is inactive, throws exception
189          */
190         private void checkIfRoleInactive(EPRole epRole) throws Exception{       
191                 if(!epRole.getActive()){
192                         throw new Exception(epRole.getName()+ " role is unavailable");
193                 }
194         }
195         
196         /**
197          * 
198          * @param sessionFactory
199          * @param userId
200          * @param appId
201          * @param userAppRoles
202          * @param extRequestValue 
203          *                      set to false if request is from users page otherwise true
204          * @throws Exception
205          */
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);
215
216                 try {
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();
228                                 
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));
238                                                 }
239                                         }
240                                 }
241
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);
245                                                 }
246                                         else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
247                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
248                                         }
249                                         else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
250                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
251                                         }
252                                 }
253                                 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
254                                 if (newRolesToAdd.size() > 0) {
255                                         EPApp app = (EPApp) localSession.get(EPApp.class, appId);
256
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; 
262                                                 }else{
263                                                         appIdValue = ""; 
264                                                 }
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) {
269                                                         role.setAppId(1L);
270                                                         rolesMap.put(role.getId(), role);
271                                                 }
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);
278                                                 }
279                                         }
280                                         EPRole role = null;
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){
287                                                                 continue;
288                                                 } else {
289                                                         userApp.setRole(rolesMap.get(userRole.getId()));        
290                                                 }
291
292                                                 userApp.setUserId(client.getId());
293                                                 userApp.setApp(app);
294                                                 localSession.save(userApp);
295                                                 localSession.flush();
296                                         }
297
298                                         if (appId == PortalConstants.PORTAL_APP_ID) {
299                                                 /*
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
307                                                  */
308                                                 SQLQuery sqlQuery = localSession
309                                                                 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
310                                                 sqlQuery.executeUpdate();
311
312                                                 
313                                         }
314                                 }
315                         }
316                         transaction.commit();
317                         result = true;
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());
324                         }
325                 } finally {
326                         localSession.close();
327                         if (!result && !"DELETE".equals(reqType)) {
328                                 throw new Exception(
329                                                 "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
330                         }
331                 }
332         }
333         
334         /**
335          * Called when getting the list of roles for the user
336          * 
337          * @param appRoles
338          * @param userAppRoles
339          * @return List<RoleInAppForUser> 
340          */
341         protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
342                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
343
344                 Set<Long> userAppRolesMap = new HashSet<Long>();
345                 if (userAppRoles != null) {
346                         for (EcompRole ecompRole : userAppRoles) {
347                                 userAppRolesMap.add(ecompRole.getId());
348                         }
349                 } else {
350                         logger.error(EELFLoggerDelegate.errorLogger,
351                                         "constructRolesInAppForUserGet has received userAppRoles list empty");
352                 }
353
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);
359                         }
360                 } else {
361                         logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
362                 }
363                 return rolesInAppForUser;
364         }
365
366         /**
367          * Called when getting the list of roles for the user
368          * 
369          * @param appRoles
370          * @param userAppRoles
371          * @param extRequestValue 
372          *                      set to false if request is from users page otherwise true
373          * @return List<RoleInAppForUser>
374          */
375         protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
376                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
377
378                 Set<Long> userAppRolesMap = new HashSet<Long>();
379                 if (userAppRoles != null) {
380                         for (EPRole ecompRole : userAppRoles) {
381                                 userAppRolesMap.add(ecompRole.getId());
382                         }
383                 } else {
384                         logger.error(EELFLoggerDelegate.errorLogger,
385                                         "constructRolesInAppForUserGet has received userAppRoles list empty.");
386                 }
387
388                 if (appRoles != null) {
389                         for (Role ecompRole : appRoles) {
390                                 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
391                                         continue;
392                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
393                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
394                                 rolesInAppForUser.add(roleForUser);
395                         }
396                 } else {
397                         logger.error(EELFLoggerDelegate.errorLogger,
398                                         "constructRolesInAppForUser has received appRoles list empty.");
399                 }
400                 return rolesInAppForUser;
401         }
402
403         
404         /**
405          * copies of methods in GetAppsWithUserRoleState
406          * 
407          * @param sessionFactory
408          * @param appId
409          * @param appRoles
410          * @throws Exception
411          */
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;
418
419                 try {
420                         localSession = sessionFactory.openSession();
421                         transaction = localSession.beginTransaction();
422                         // Attention! All roles from remote application supposed to be
423                         // active!
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());
433                                         if (role != null) {
434                                                 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
435                                                         oldAppRole.setName(role.getName());
436                                                         localSession.update(oldAppRole);
437                                                 }
438                                                 newRolesMap.remove(oldAppRole.getAppRoleId());
439                                         } else {
440                                                 obsoleteRoles.add(oldAppRole);
441                                         }
442                                 } else {
443                                         obsoleteRoles.add(oldAppRole);
444                                 }
445                         }
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
451                                 // active!
452                                 newRole.setActive(true);
453                                 newRole.setName(role.getName());
454                                 newRole.setAppId(appId);
455                                 newRole.setAppRoleId(role.getId());
456                                 localSession.save(newRole);
457                         }
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
465                                         // fn_role:
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.
470
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)
475                                                         .list();
476
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());
484                                         }
485
486                                         // Delete from fn_menu_functional_roles
487                                         @SuppressWarnings("unchecked")
488                                         List<FunctionalMenuRole> funcMenuRoles = localSession
489                                                         .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
490                                                         .list();
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)
502                                                                 .list();
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
515                                                                         .createQuery(
516                                                                                         "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
517                                                                         .list();
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);
523                                                         }
524                                                 }
525                                         }
526
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();
532                                         
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();
538                                         
539                                         // Delete from fn_role_composite
540                                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id="
541                                                         + roleId;
542                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
543                                         query = localSession.createSQLQuery(sql);
544                                         query.executeUpdate();
545
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();
551
552                                         logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString());
553                                         localSession.delete(role);
554                                         logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role");
555                                 }
556                         }
557                         logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
558                         transaction.commit();
559                         logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
560                         result = true;
561                 } catch (Exception e) {
562                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
563                         EcompPortalUtils.rollbackTransaction(transaction,
564                                         "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e));
565                 } finally {
566                         localSession.close();
567                         if (!result) {
568                                 throw new Exception(
569                                                 "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'.");
570                         }
571                 }
572         }
573         
574         /**
575          * Called when updating the list of roles for the user
576          * 
577          * @param userId
578          * @param appId
579          * @param userRolesInRemoteApp
580          * @return RolesInAppForUser
581          */
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);
594                 }
595                 return result;
596         }
597         
598         /**
599          * 
600          * @param roleInAppForUserList
601          * @return boolean
602          */
603         protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
604                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
605                         if (roleInAppForUser.isApplied.booleanValue()) {
606                                 return true;
607                         }
608                 }
609                 return false;
610         }
611         
612         /**
613          * Builds JSON and posts it to a remote application to update user roles.
614          * 
615          * @param roleInAppForUserList
616          * @param mapper
617          * @param applicationsRestClientService
618          * @param appId
619          * @param userId
620          * @return Set of roles as sent; NOT the response from the app.
621          * @throws JsonProcessingException
622          * @throws HTTPException
623          */
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;
636         }
637         
638         /**
639          * 
640          * @param roleInAppForUserList
641          * @return Set<EcompRole> 
642          */
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);
651                         }
652                 }
653                 return existingUserRoles;
654         }
655         
656         /**
657          * Constructs user app roles excluding Account Administrator role
658          * 
659          * @param roleInAppForUserList
660          * @return
661          *            List of roles with Role name, Role Id
662          */
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);
671                         }
672                 }
673                 return existingUserRoles;
674         }
675         
676         /**
677          * This is for a single app
678          * 
679          * @param rolesInAppForUser
680          * @param externalSystemRequest  
681          *                      set to false if requests from Users page otherwise true
682          * @return true on success, false otherwise
683          */
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);
691                         }
692
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;
701                                 }
702                                 try {
703                                         syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
704                                         result = true;
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());
710                                         }
711                                 }
712                         }
713                 }
714                 return result;
715         }
716         
717         /**
718          * 
719          * @param appId
720          * @param remoteUser
721          * @return UserApplicationRoles
722          */
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;
731         }
732         
733         /*
734          * (non-Javadoc)
735          * 
736          * @see org.openecomp.portalapp.portal.service.UserRolesService#
737          * importRolesFromRemoteApplication(java.lang.Long)
738          */
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) {
743
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));
753                                 continue;
754                         }
755                         // persistExternalRoleInEcompDb(externalAppRole, appId,
756                         // roleService);
757                 }
758
759                 return rolesList;
760         }
761         
762         /*
763          * (non-Javadoc)
764          * 
765          * @see org.openecomp.portalapp.portal.service.UserRolesService#
766          * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
767          * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
768          */
769         public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
770                 boolean result = false;
771                 boolean epRequestValue = false;
772                 String userId = "";
773                 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
774                         userId = newAppRolesForUser.orgUserId.trim();
775                 }
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);
781
782                         try {
783                                 EPApp app = appsService.getApp(appId);
784                                 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
785
786                                 // if local app
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);
794
795                                 } else {// remote app
796                                         EPUser remoteAppUser = null;
797                                         try {
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",
804                                                                         e);
805                                                 } else {
806                                                         // Other response code, let it come thru.
807                                                         throw e;
808                                                 }
809                                         }
810                                         if (remoteAppUser == null) {
811                                                 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
812                                                         
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);
820                                                                 // return null;
821                                                         }
822                                                 }
823                                         }
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);
830
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,
835                                                                         userId);
836                                                         remoteAppUser.setActive(false);
837                                                         postUserToRemoteApp(userId, user, app, applicationsRestClientService);
838                                                 }
839                                         }
840                                 }
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);
846                                 result = false;
847                         }
848
849                 }
850                 return result;
851         }
852         
853         /**
854          * 
855          * @param userId
856          * @param app
857          * @param applicationsRestClientService
858          * @param searchService
859          * @param mapper
860          * @throws Exception
861          */
862         protected void createNewUserOnRemoteApp(String userId, EPApp app,
863                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
864                         ObjectMapper mapper, boolean postOpenSource) throws Exception {
865
866                         
867                         EPUser client = searchService.searchUserByUserId(userId);
868                         
869                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
870                         
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);
875                         }
876
877                         client.setLoginId(userId);
878                         client.setActive(true);
879
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));
885
886         }
887         
888         @SuppressWarnings("unchecked")
889         protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
890                 final Map<String, Long> epRequestParams = new HashMap<>();
891                 try {
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);
910                                 }
911                         }
912                         logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
913
914                 } catch (Exception e) {
915                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
916                 }
917         }
918         
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());
926                 try {
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);
948                                         }
949                                         logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
950                                 }
951                         }
952
953                 } catch (Exception e) {
954                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
955                 }
956         }
957         
958         /**
959          * Pushes specified user details to the specified remote app.
960          * 
961          * @param userId
962          *            OrgUserId identifying user at remote app in REST endpoint path
963          * @param user
964          *            User details to be pushed
965          * @param app
966          *            Remote app
967          * @param applicationsRestClientService
968          * @throws HTTPException
969          */
970         protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
971                         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
972         
973                  getUser(userId, app, applicationsRestClientService);
974                                         
975         }
976         
977         /**
978          * It returns user details for single org user id
979          * 
980          * @param userParams
981          * @return
982          *              if user exists it returns list of user details otherwise empty value
983          */
984         @SuppressWarnings("unchecked")
985         private List<EPUser> checkIfUserExists(Map<String, String> userParams){ 
986                 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
987         }
988         
989         /**
990          * It checks whether the new user is valid or not otherwise throws exception
991          * 
992          * @param orgUserId
993          * @param app
994          * @return 
995          *                      Checks if user is valid and returns message otherwise throws exception
996          * @throws Exception
997          */
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");
1006                 }
1007                 return "Saved Successfully";
1008         }
1009         
1010         /**
1011          *   Checks if the fields exists or not
1012          *   
1013          * @param userList
1014          *                      contains user information
1015          * @param app
1016          *                      contains app name
1017          * @throws Exception
1018          *                      throws exception if the field is not valid
1019          */
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");
1027                 }
1028         }
1029         
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 = "";
1042                 EPApp app = null;
1043                 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1044                         orgUserId = newAppRolesForUser.getLoginId().trim();
1045                 }
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;
1052                         try {
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);
1059                                 }
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();
1068                                 }
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);
1072                                 }
1073                                 
1074                                 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1075                                                 app.getId(), app.getMlAppName());
1076                                 // if local app
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;
1088                                         try {
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",
1095                                                                         e);
1096                                                 } else {
1097                                                         // Other response code, let it come thru.
1098                                                         throw e;
1099                                                 }
1100                                         }
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());
1110                                                         // return null;
1111                                                 }
1112                                                 reqMessage = "Saved Successfully";
1113                                         }
1114                                         if (remoteAppUser != null) {
1115                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1116                                                                                         mapper, applicationsRestClientService, app.getId(), orgUserId); 
1117                                                         
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,
1127                                                                                 orgUserId);
1128                                                                 //TODO Need  to fix the logged in user is not set to inactive
1129                                                                 remoteAppUser.setActive(false);
1130                                                                 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
1131                                                         }*/
1132
1133                                         }
1134                                         if(!result){
1135                                                 reqMessage = "Failed to save the user app role(s)";
1136                                         }
1137                                         if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1138                                                 updateStatus = "C";
1139                                                 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1140                                         }
1141                                         
1142                                 }
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);
1147                                 result = false;
1148                                 reqMessage = e.getMessage();
1149                                  if(epRequestIdSize > 0 && !userInfo.isEmpty()){
1150                                  updateStatus = "F";
1151                                  applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1152                                  updateStatus, epRequestId.get(0));
1153                                  }
1154                         }
1155
1156                 }
1157                 return new ExternalRequestFieldsValidator(result, reqMessage);
1158         }
1159         
1160         /**
1161          * 
1162          * @param roleInAppForUserList
1163          * @param mapper
1164          * @param applicationsRestClientService
1165          * @param appId
1166          * @param userId
1167          * @return  Set<EcompRole>
1168          * @throws JsonProcessingException
1169          * @throws HTTPException
1170          */
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;
1176         }
1177         
1178         /**
1179          * It constructs and returns list of user app roles when the external API role approval system calls
1180          * this method
1181          * 
1182          * @param roleInAppForUserList
1183          * @param appId
1184          * @return list of user app roles
1185          * @throws Exception
1186          *                 throws exceptions if role id does not exits 
1187          */
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");
1199                         }
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");
1204                         } else {
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);
1209                         }
1210                 }
1211                 return existingUserRoles;
1212         }
1213         
1214         
1215
1216         /**
1217          * 
1218          * @param userId
1219          * @param app
1220          * @param applicationsRestClientService
1221          * @return EPUser
1222          * @throws HTTPException
1223          */
1224         protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1225                         throws HTTPException {
1226                 // local app
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);
1235                         else
1236                                 return null;
1237                 }
1238                 // remote app
1239                 
1240                 return getUser(userId, app, applicationsRestClientService);
1241         }
1242         
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), true);
1246
1247         }
1248         
1249         protected boolean isAppUpgradeVersion(EPApp app){
1250                 return true;
1251         }
1252         
1253         
1254         public ExternalSystemAccess getExternalRequestAccess(){
1255                 ExternalSystemAccess res = null; 
1256                 try {
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());
1261                 }
1262                 return res;             
1263         }
1264         
1265         /*
1266          * (non-Javadoc)
1267          * 
1268          * @see org.openecomp.portalapp.portal.service.UserRolesService#
1269          * getAppRolesForUser(java.lang.Long, java.lang.String)
1270          */
1271         public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1272
1273                 List<RoleInAppForUser> rolesInAppForUser = null;
1274                 List<EPUser> userInfo = null;
1275                 try {
1276
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())
1283                                 {
1284                                         createLocalUserIfNecessary(userId);
1285                                 }
1286
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);
1295                                                 }
1296                                         }
1297                                                 
1298                                 }
1299                                 
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;
1305                         }
1306
1307                         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1308
1309                         // Test this error case, for generating an internal Ecomp Portal
1310                         // error
1311                         // EcompRole[] appRoles = null;
1312                         // If there is an exception in the rest client api, then null will
1313                         // be returned.
1314                         if (appRoles != null) {
1315                                 syncAppRoles(sessionFactory, appId, appRoles);
1316                                 EcompRole[] userAppRoles = null;
1317                                 try {
1318                                         try {
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);
1326                                                 } else {
1327                                                         // Other response code, let it come thru.
1328                                                         throw e;
1329                                                 }
1330                                         }
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);
1340                                                 }
1341                                         }
1342                                         
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);
1351                                                         }
1352                                                 }
1353                                                 EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1354                                         
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
1360                                         // app is down.
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];
1366                                 }
1367                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1368                         }
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);
1373                 }
1374                 return rolesInAppForUser;
1375
1376         }
1377         
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));
1387                 return result;
1388         }
1389
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();
1394                 try {
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());
1397                         
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);                           
1411                                 if (isAppliedVal) {
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);
1418                                         }                       
1419                         }
1420                         epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1421                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1422
1423                 } catch (Exception e) {
1424                         logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1425                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1426                 }
1427                 return fieldsValidator;
1428         }
1429
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);
1435                         
1436                 @SuppressWarnings("unchecked")
1437                 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1438                                 .executeNamedQuery("userAppCatalogRoles", params, null);
1439                 return userAppRoles;    
1440         }
1441         
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());
1455                 try {
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) {
1461                                 try {
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());
1467                                 }
1468                         }
1469                 } catch (Exception e) {
1470                         logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1471                         return "failure";
1472                 }
1473
1474                 return "success";
1475         }
1476
1477
1478         /*
1479          * (non-Javadoc)
1480          * 
1481          * @see org.openecomp.portalapp.portal.service.UserRolesService#
1482          * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1483          */
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());
1490                 return roleList;
1491         }
1492
1493 }