[PORTAL-16 PORTAL-18] Widget ms; staging
[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){
247                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
248                                         }
249                                 }
250                                 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
251                                 if (newRolesToAdd.size() > 0) {
252                                         EPApp app = (EPApp) localSession.get(EPApp.class, appId);
253
254                                         HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
255                                         if (appId == PortalConstants.PORTAL_APP_ID) { // local app
256                                                 String appIdValue = null;
257                                                 if(!extRequestValue){
258                                                         appIdValue = "and id != " +  PortalConstants.PORTAL_APP_ID; 
259                                                 }else{
260                                                         appIdValue = ""; 
261                                                 }
262                                                 @SuppressWarnings("unchecked")
263                                                 List<EPRole> roles = localSession
264                                                                 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
265                                                 for (EPRole role : roles) {
266                                                         role.setAppId(1L);
267                                                         rolesMap.put(role.getId(), role);
268                                                 }
269                                         } else { // remote app
270                                                 @SuppressWarnings("unchecked")
271                                                 List<EPRole> roles = localSession
272                                                                 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
273                                                 for (EPRole role : roles) {
274                                                         rolesMap.put(role.getAppRoleId(), role);
275                                                 }
276                                         }
277                                         EPRole role = null;
278                                         for (EcompRole userRole : newRolesToAdd) {
279                                                 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
280                                                         role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
281                                                 } else if (userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue){
282                                                                 continue;
283                                                 }
284                                                 EPUserApp userApp = new EPUserApp();
285                                                 userApp.setUserId(client.getId());
286                                                 userApp.setApp(app);
287                                                 userApp.setRole(("PUT".equals(reqType) || "POST".equals(reqType) && userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) ?  role : rolesMap.get(userRole.getId()));
288                                                 localSession.save(userApp);
289                                                 localSession.flush();
290                                         }
291
292                                         if (appId == PortalConstants.PORTAL_APP_ID) {
293                                                 /*
294                                                  * for local app -- hack - always make sure fn_role
295                                                  * table's app_id is null and not 1 for primary app in
296                                                  * this case being ecomp portal app; reason: hibernate
297                                                  * is rightly setting this to 1 while persisting to
298                                                  * fn_role as per the mapping but SDK role management
299                                                  * code expects the app_id to be null as there is no
300                                                  * concept of App_id in SDK
301                                                  */
302                                                 SQLQuery sqlQuery = localSession
303                                                                 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
304                                                 sqlQuery.executeUpdate();
305
306                                                 
307                                         }
308                                 }
309                         }
310                         transaction.commit();
311                         result = true;
312                 } catch (Exception e) {
313                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
314                         EcompPortalUtils.rollbackTransaction(transaction,
315                                         "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e));
316                         if("DELETE".equals(reqType)){
317                                 throw new Exception(e.getMessage());
318                         }
319                 } finally {
320                         localSession.close();
321                         if (!result && !"DELETE".equals(reqType)) {
322                                 throw new Exception(
323                                                 "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
324                         }
325                 }
326         }
327         
328         /**
329          * Called when getting the list of roles for the user
330          * 
331          * @param appRoles
332          * @param userAppRoles
333          * @return List<RoleInAppForUser> 
334          */
335         protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
336                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
337
338                 Set<Long> userAppRolesMap = new HashSet<Long>();
339                 if (userAppRoles != null) {
340                         for (EcompRole ecompRole : userAppRoles) {
341                                 userAppRolesMap.add(ecompRole.getId());
342                         }
343                 } else {
344                         logger.error(EELFLoggerDelegate.errorLogger,
345                                         "constructRolesInAppForUserGet has received userAppRoles list empty");
346                 }
347
348                 if (appRoles != null) {
349                         for (EcompRole ecompRole : appRoles) {
350                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
351                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
352                                 rolesInAppForUser.add(roleForUser);
353                         }
354                 } else {
355                         logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
356                 }
357                 return rolesInAppForUser;
358         }
359
360         /**
361          * Called when getting the list of roles for the user
362          * 
363          * @param appRoles
364          * @param userAppRoles
365          * @param extRequestValue 
366          *                      set to false if request is from users page otherwise true
367          * @return List<RoleInAppForUser>
368          */
369         protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
370                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
371
372                 Set<Long> userAppRolesMap = new HashSet<Long>();
373                 if (userAppRoles != null) {
374                         for (EPRole ecompRole : userAppRoles) {
375                                 userAppRolesMap.add(ecompRole.getId());
376                         }
377                 } else {
378                         logger.error(EELFLoggerDelegate.errorLogger,
379                                         "constructRolesInAppForUserGet has received userAppRoles list empty.");
380                 }
381
382                 if (appRoles != null) {
383                         for (Role ecompRole : appRoles) {
384                                 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
385                                         continue;
386                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
387                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
388                                 rolesInAppForUser.add(roleForUser);
389                         }
390                 } else {
391                         logger.error(EELFLoggerDelegate.errorLogger,
392                                         "constructRolesInAppForUser has received appRoles list empty.");
393                 }
394                 return rolesInAppForUser;
395         }
396
397         
398         /**
399          * copies of methods in GetAppsWithUserRoleState
400          * 
401          * @param sessionFactory
402          * @param appId
403          * @param appRoles
404          * @throws Exception
405          */
406         protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
407                 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
408                 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
409                 boolean result = false;
410                 Session localSession = null;
411                 Transaction transaction = null;
412
413                 try {
414                         localSession = sessionFactory.openSession();
415                         transaction = localSession.beginTransaction();
416                         // Attention! All roles from remote application supposed to be
417                         // active!
418                         @SuppressWarnings("unchecked")
419                         List<EPRole> currentAppRoles = localSession
420                                         .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
421                         List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
422                         for (int i = 0; i < currentAppRoles.size(); i++) {
423                                 EPRole oldAppRole = currentAppRoles.get(i);
424                                 if (oldAppRole.getAppRoleId() != null) {
425                                         EcompRole role = null;
426                                         role = newRolesMap.get(oldAppRole.getAppRoleId());
427                                         if (role != null) {
428                                                 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
429                                                         oldAppRole.setName(role.getName());
430                                                         localSession.update(oldAppRole);
431                                                 }
432                                                 newRolesMap.remove(oldAppRole.getAppRoleId());
433                                         } else {
434                                                 obsoleteRoles.add(oldAppRole);
435                                         }
436                                 } else {
437                                         obsoleteRoles.add(oldAppRole);
438                                 }
439                         }
440                         Collection<EcompRole> newRolesToAdd = newRolesMap.values();
441                         for (EcompRole role : newRolesToAdd) {
442                                 logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString());
443                                 EPRole newRole = new EPRole();
444                                 // Attention! All roles from remote application supposed to be
445                                 // active!
446                                 newRole.setActive(true);
447                                 newRole.setName(role.getName());
448                                 newRole.setAppId(appId);
449                                 newRole.setAppRoleId(role.getId());
450                                 localSession.save(newRole);
451                         }
452                         if (obsoleteRoles.size() > 0) {
453                                 logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete");
454                                 for (EPRole role : obsoleteRoles) {
455                                         logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString());
456                                         Long roleId = role.getId();
457                                         // delete obsolete roles here
458                                         // Must delete all records with foreign key constraints on
459                                         // fn_role:
460                                         // fn_user_role, fn_role_composite, fn_role_function,
461                                         // fn_user_pseudo_role, fn_menu_functional_roles.
462                                         // And for fn_menu_functional, if no other roles for that
463                                         // menu item, remove the url.
464
465                                         // Delete from fn_user_role
466                                         @SuppressWarnings("unchecked")
467                                         List<EPUserApp> userRoles = localSession.createQuery(
468                                                         "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
469                                                         .list();
470
471                                         logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size());
472                                         for (EPUserApp userRole : userRoles) {
473                                                 logger.debug(EELFLoggerDelegate.debugLogger,
474                                                                 "about to delete userRole: " + userRole.toString());
475                                                 localSession.delete(userRole);
476                                                 logger.debug(EELFLoggerDelegate.debugLogger,
477                                                                 "finished deleting userRole: " + userRole.toString());
478                                         }
479
480                                         // Delete from fn_menu_functional_roles
481                                         @SuppressWarnings("unchecked")
482                                         List<FunctionalMenuRole> funcMenuRoles = localSession
483                                                         .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
484                                                         .list();
485                                         int numMenuRoles = funcMenuRoles.size();
486                                         logger.debug(EELFLoggerDelegate.debugLogger,
487                                                         "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
488                                         for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
489                                                 Long menuId = funcMenuRole.menuId;
490                                                 // If this is the only role for this menu item, then the
491                                                 // app and roles will be gone,
492                                                 // so must null out the url too, to be consistent
493                                                 @SuppressWarnings("unchecked")
494                                                 List<FunctionalMenuRole> funcMenuRoles2 = localSession
495                                                                 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
496                                                                 .list();
497                                                 int numMenuRoles2 = funcMenuRoles2.size();
498                                                 logger.debug(EELFLoggerDelegate.debugLogger,
499                                                                 "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
500                                                 localSession.delete(funcMenuRole);
501                                                 if (numMenuRoles2 == 1) {
502                                                         // If this is the only role for this menu item, then
503                                                         // the app and roles will be gone,
504                                                         // so must null out the url too, to be consistent
505                                                         logger.debug(EELFLoggerDelegate.debugLogger,
506                                                                         "There is exactly 1 menu item for this role, so emptying the url");
507                                                         @SuppressWarnings("unchecked")
508                                                         List<FunctionalMenuItem> funcMenuItems = localSession
509                                                                         .createQuery(
510                                                                                         "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
511                                                                         .list();
512                                                         if (funcMenuItems.size() > 0) {
513                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
514                                                                 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
515                                                                 funcMenuItem.url = "";
516                                                                 localSession.update(funcMenuItem);
517                                                         }
518                                                 }
519                                         }
520
521                                         // Delete from fn_role_function
522                                         String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
523                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
524                                         Query query = localSession.createSQLQuery(sql);
525                                         query.executeUpdate();
526                                         
527                                         // Delete from ep_role_notification
528                                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
529                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
530                                         query = localSession.createSQLQuery(sql);
531                                         query.executeUpdate();
532                                         
533                                         // Delete from fn_role_composite
534                                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id="
535                                                         + roleId;
536                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
537                                         query = localSession.createSQLQuery(sql);
538                                         query.executeUpdate();
539
540                                         // Delete from fn_user_pseudo_role
541                                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
542                                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
543                                         query = localSession.createSQLQuery(sql);
544                                         query.executeUpdate();
545
546                                         logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString());
547                                         localSession.delete(role);
548                                         logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role");
549                                 }
550                         }
551                         logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
552                         transaction.commit();
553                         logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
554                         result = true;
555                 } catch (Exception e) {
556                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
557                         EcompPortalUtils.rollbackTransaction(transaction,
558                                         "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e));
559                 } finally {
560                         localSession.close();
561                         if (!result) {
562                                 throw new Exception(
563                                                 "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'.");
564                         }
565                 }
566         }
567         
568         /**
569          * Called when updating the list of roles for the user
570          * 
571          * @param userId
572          * @param appId
573          * @param userRolesInRemoteApp
574          * @return RolesInAppForUser
575          */
576         protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
577                         Set<EcompRole> userRolesInRemoteApp) {
578                 RolesInAppForUser result;
579                 result = new RolesInAppForUser();
580                 result.appId = appId;
581                 result.orgUserId = userId;
582                 for (EcompRole role : userRolesInRemoteApp) {
583                         RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
584                         roleInAppForUser.roleId = role.getId();
585                         roleInAppForUser.roleName = role.getName();
586                         roleInAppForUser.isApplied = new Boolean(true);
587                         result.roles.add(roleInAppForUser);
588                 }
589                 return result;
590         }
591         
592         /**
593          * 
594          * @param roleInAppForUserList
595          * @return boolean
596          */
597         protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
598                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
599                         if (roleInAppForUser.isApplied.booleanValue()) {
600                                 return true;
601                         }
602                 }
603                 return false;
604         }
605         
606         /**
607          * Builds JSON and posts it to a remote application to update user roles.
608          * 
609          * @param roleInAppForUserList
610          * @param mapper
611          * @param applicationsRestClientService
612          * @param appId
613          * @param userId
614          * @return Set of roles as sent; NOT the response from the app.
615          * @throws JsonProcessingException
616          * @throws HTTPException
617          */
618         protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
619                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
620                         throws JsonProcessingException, HTTPException {
621                 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
622                 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
623                 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
624                 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
625                                 String.format("/user/%s/roles", userId));
626                 // TODO: We should add code that verifies that the post operation did
627                 // succeed. Because the SDK may still return 200 OK with an html page
628                 // even when it fails!
629                 return updateUserRolesInEcomp;
630         }
631         
632         /**
633          * 
634          * @param roleInAppForUserList
635          * @return Set<EcompRole> 
636          */
637         protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
638                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
639                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
640                         if (roleInAppForUser.isApplied) {
641                                 EcompRole ecompRole = new EcompRole();
642                                 ecompRole.setId(roleInAppForUser.roleId);
643                                 ecompRole.setName(roleInAppForUser.roleName);
644                                 existingUserRoles.add(ecompRole);
645                         }
646                 }
647                 return existingUserRoles;
648         }
649         
650         /**
651          * Constructs user app roles excluding Account Administrator role
652          * 
653          * @param roleInAppForUserList
654          * @return
655          *            List of roles with Role name, Role Id
656          */
657         protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
658                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
659                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
660                         if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
661                                 EcompRole ecompRole = new EcompRole();
662                                 ecompRole.setId(roleInAppForUser.roleId);
663                                 ecompRole.setName(roleInAppForUser.roleName);
664                                 existingUserRoles.add(ecompRole);
665                         }
666                 }
667                 return existingUserRoles;
668         }
669         
670         /**
671          * This is for a single app
672          * 
673          * @param rolesInAppForUser
674          * @param externalSystemRequest  
675          *                      set to false if requests from Users page otherwise true
676          * @return true on success, false otherwise
677          */
678         protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
679                 boolean result = false;
680                 String userId = rolesInAppForUser.orgUserId;
681                 Long appId = rolesInAppForUser.appId;
682                 synchronized (syncRests) {
683                         if (rolesInAppForUser != null) {
684                                 createLocalUserIfNecessary(userId);
685                         }
686
687                         if (rolesInAppForUser != null) {
688                                 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()];
689                                 for (int i = 0; i < rolesInAppForUser.roles.size(); i++) {
690                                         RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
691                                         EcompRole role = new EcompRole();
692                                         role.setId(roleInAppForUser.roleId);
693                                         role.setName(roleInAppForUser.roleName);
694                                         userAppRoles[i] = role;
695                                 }
696                                 try {
697                                         syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
698                                         result = true;
699                                 } catch (Exception e) {
700                                         logger.error(EELFLoggerDelegate.errorLogger,
701                                                         "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for attuid " + userId, e);
702                                         if("DELETE".equals(reqType)){
703                                                 throw new Exception(e.getMessage());
704                                         }
705                                 }
706                         }
707                 }
708                 return result;
709         }
710         
711         /**
712          * 
713          * @param appId
714          * @param remoteUser
715          * @return UserApplicationRoles
716          */
717         protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
718                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
719                 userWithRemoteAppRoles.setAppId(appId);
720                 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
721                 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
722                 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
723                 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
724                 return userWithRemoteAppRoles;
725         }
726         
727         /*
728          * (non-Javadoc)
729          * 
730          * @see org.openecomp.portalapp.portal.service.UserRolesService#
731          * importRolesFromRemoteApplication(java.lang.Long)
732          */
733         public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
734                 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
735                 List<EPRole> rolesList = Arrays.asList(appRolesFull);
736                 for (EPRole externalAppRole : rolesList) {
737
738                         // Try to find an existing extern role for the app in the local
739                         // ecomp DB. If so, then use its id to update the existing external
740                         // application role record.
741                         Long externAppId = externalAppRole.getId();
742                         EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
743                         if (existingAppRole != null) {
744                                 logger.debug(EELFLoggerDelegate.debugLogger,
745                                                 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
746                                                                 appId, externAppId));
747                                 continue;
748                         }
749                         // persistExternalRoleInEcompDb(externalAppRole, appId,
750                         // roleService);
751                 }
752
753                 return rolesList;
754         }
755         
756         /*
757          * (non-Javadoc)
758          * 
759          * @see org.openecomp.portalapp.portal.service.UserRolesService#
760          * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
761          * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
762          */
763         public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
764                 boolean result = false;
765                 boolean epRequestValue = false;
766                 String userId = "";
767                 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
768                         userId = newAppRolesForUser.orgUserId.trim();
769                 }
770                 Long appId = newAppRolesForUser.appId;
771                 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
772                 if (userId.length() > 0) {
773                         ObjectMapper mapper = new ObjectMapper();
774                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
775
776                         try {
777                                 EPApp app = appsService.getApp(appId);
778                                 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
779
780                                 // if local app
781                                 if (appId == PortalConstants.PORTAL_APP_ID) {
782                                         // EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
783                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
784                                                         applicationsRestClientService, appId, userId);
785                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
786                                                         userRolesInLocalApp);
787                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
788
789                                 } else {// remote app
790                                         EPUser remoteAppUser = null;
791                                         try {
792                                                 remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService);
793                                         } catch (HTTPException e) {
794                                                 // Some apps are returning 400 if user is not found.
795                                                 if (e.getResponseCode() == 400) {
796                                                         logger.debug(EELFLoggerDelegate.debugLogger,
797                                                                         "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
798                                                                         e);
799                                                 } else {
800                                                         // Other response code, let it come thru.
801                                                         throw e;
802                                                 }
803                                         }
804                                         if (remoteAppUser == null) {
805                                                 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
806                                                         
807                                                         createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
808                                                         // If we succeed, we know that the new user was
809                                                         // persisted on remote app.
810                                                         remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService);
811                                                         if (remoteAppUser == null) {
812                                                                 logger.error(EELFLoggerDelegate.errorLogger,
813                                                                                 "Failed to persist new user: " + userId + " in remote app. appId = " + appId);
814                                                                 // return null;
815                                                         }
816                                                 }
817                                         }
818                                         if (remoteAppUser != null) {
819                                                 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
820                                                                 applicationsRestClientService, appId, userId);
821                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
822                                                                 userRolesInRemoteApp);
823                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
824
825                                                 // If no roles remain, request app to set user inactive.
826                                                 if (userRolesInRemoteApp.size() == 0) {
827                                                         logger.debug(EELFLoggerDelegate.debugLogger,
828                                                                         "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
829                                                                         userId);
830                                                         remoteAppUser.setActive(false);
831                                                         postUserToRemoteApp(userId, user, app, applicationsRestClientService);
832                                                 }
833                                         }
834                                 }
835                         } catch (Exception e) {
836                                 String message = String.format(
837                                                 "Failed to create user or update user roles for User %s, AppId %s",
838                                                 userId, Long.toString(appId));
839                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
840                                 result = false;
841                         }
842
843                 }
844                 return result;
845         }
846         
847         /**
848          * 
849          * @param userId
850          * @param app
851          * @param applicationsRestClientService
852          * @param searchService
853          * @param mapper
854          * @throws Exception
855          */
856         protected void createNewUserOnRemoteApp(String userId, EPApp app,
857                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
858                         ObjectMapper mapper, boolean postOpenSource) throws Exception {
859
860                         
861                         EPUser client = searchService.searchUserByUserId(userId);
862                         
863                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
864                         
865                         if (client == null) {
866                                 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
867                                 logger.error(EELFLoggerDelegate.errorLogger, msg);
868                                 throw new Exception(msg);
869                         }
870
871                         client.setLoginId(userId);
872                         client.setActive(true);
873
874                         String userInString = null;
875                         userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
876                         logger.debug(EELFLoggerDelegate.debugLogger,
877                                         "about to post new client to remote application, users json = " + userInString);
878                         applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
879
880         }
881         
882         @SuppressWarnings("unchecked")
883         protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
884                 final Map<String, Long> epRequestParams = new HashMap<>();
885                 try {
886                         EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
887                         epAppRolesRequestData.setUpdatedDate(new Date());
888                         epAppRolesRequestData.setRequestStatus(updateStatus);
889                         HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
890                         addiotonalUpdateParam.put("userId", userId);
891                         dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
892                         epRequestParams.put("reqId", epUserAppRolesRequest.getId());
893                         List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
894                         epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
895                                         epRequestParams, null);
896                         if (epUserAppRolessDetailList.size() > 0) {
897                                 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
898                                         EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
899                                         epAppRoleDetailData.setReqType(updateStatus);
900                                         epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
901                                         HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
902                                         addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
903                                         dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
904                                 }
905                         }
906                         logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
907
908                 } catch (Exception e) {
909                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
910                 }
911         }
912         
913         @SuppressWarnings("unchecked")
914         public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
915                 final Map<String, Long> params = new HashMap<>();
916                 final Map<String, Long> epDetailParams = new HashMap<>();
917                 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
918                 params.put("appId", appId);
919                 params.put("userId", user.getId());
920                 try {
921                         epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
922                                         .executeNamedQuery("userAppRolesRequestList", params, null);
923                         if (epRequestIdVal.size() > 0) {
924                                 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
925                                 epAppRolesRequestData.setUpdatedDate(new Date());
926                                 epAppRolesRequestData.setRequestStatus("O");
927                                 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
928                                 addiotonalUpdateParam.put("userId", user.getId());
929                                 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
930                                 epDetailParams.put("reqId", epAppRolesRequestData.getId());
931                                 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
932                                 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
933                                                 epDetailParams, null);
934                                 if (epUserAppRolesDetailList.size() > 0) {
935                                         for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
936                                                 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
937                                                 epAppRoleDetailData.setReqType("O");
938                                                 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
939                                                 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
940                                                 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
941                                                 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
942                                         }
943                                         logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
944                                 }
945                         }
946
947                 } catch (Exception e) {
948                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
949                 }
950         }
951         
952         /**
953          * Pushes specified user details to the specified remote app.
954          * 
955          * @param userId
956          *            ATT UID identifying user at remote app in REST endpoint path
957          * @param user
958          *            User details to be pushed
959          * @param app
960          *            Remote app
961          * @param applicationsRestClientService
962          * @throws HTTPException
963          */
964         protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
965                         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
966         
967                  getUser(userId, app, applicationsRestClientService);
968                                         
969         }
970         
971         /**
972          * It returns user details for single org user id
973          * 
974          * @param userParams
975          * @return
976          *              if user exists it returns list of user details otherwise empty value
977          */
978         @SuppressWarnings("unchecked")
979         private List<EPUser> checkIfUserExists(Map<String, String> userParams){ 
980                 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
981         }
982         
983         /**
984          * It checks whether the new user is valid or not otherwise throws exception
985          * 
986          * @param orgUserId
987          * @param app
988          * @return 
989          *                      Checks if user is valid and returns message otherwise throws exception
990          * @throws Exception
991          */
992         private String validateNewUser(String orgUserId, EPApp app) throws Exception {
993                 EPUser epUser = searchService.searchUserByUserId(orgUserId);
994                 if (epUser == null) {
995                         throw new Exception("User does not exist");
996                 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
997                         throw new Exception("User does not exist");
998                 } else if (app == null) {
999                         throw new Exception("Application does not exist");
1000                 }
1001                 return "Saved Successfully";
1002         }
1003         
1004         /**
1005          *   Checks if the fields exists or not
1006          *   
1007          * @param userList
1008          *                      contains user information
1009          * @param app
1010          *                      contains app name
1011          * @throws Exception
1012          *                      throws exception if the field is not valid
1013          */
1014         private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1015                 if (userList.size() == 0 || userList.isEmpty() ) {
1016                         throw new Exception("User does not exist");
1017                 } else if(app == null) {
1018                         throw new Exception("Application does not exist");
1019                 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1020                         throw new Exception(app.getMlAppName()+" application is unavailable");
1021                 }
1022         }
1023         
1024         @SuppressWarnings("unchecked")
1025         public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1026                 boolean result = false;
1027                 boolean externalSystemRequest = true;
1028                 final Map<String, Long> params = new HashMap<>();
1029                 final Map<String, String> userParams = new HashMap<>();
1030                 List<EPUser> userInfo = null;
1031                 EPUser userId = null;
1032                 List<EPUserAppRolesRequest> epRequestId = null;
1033                 String orgUserId = "";
1034                 String updateStatus = "";
1035                 String reqMessage = "";
1036                 EPApp app = null;
1037                 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1038                         orgUserId = newAppRolesForUser.getLoginId().trim();
1039                 }
1040                 String appName = newAppRolesForUser.getApplicationName();
1041                 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1042                 if (orgUserId.length() > 0) {
1043                         ObjectMapper mapper = new ObjectMapper();
1044                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1045                         int epRequestIdSize = 0;
1046                         try {
1047                                 app = appsService.getAppDetail(appName);
1048                                 userParams.put("orgUserIdValue", orgUserId);
1049                                 userInfo = checkIfUserExists(userParams);
1050                                 reqMessage = "Updated Successfully";
1051                                 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1052                                         reqMessage = validateNewUser(orgUserId, app);
1053                                 }
1054                                 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1055                                         validateExternalRequestFields(userInfo, app);
1056                                         userId = userInfo.get(0);
1057                                         params.put("appId", app.getId());
1058                                         params.put("userId", userId.getId());
1059                                         epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1060                                                         .executeNamedQuery("userAppRolesRequestList", params, null);
1061                                         epRequestIdSize = epRequestId.size();
1062                                 }
1063                                 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)){ 
1064                                 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1065                                 syncAppRoles(sessionFactory, app.getId(), appRoles);
1066                                 }
1067                                 
1068                                 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1069                                                 app.getId(), app.getMlAppName());
1070                                 // if local app
1071                                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1072                                         // EPUser localUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
1073                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1074                                                         applicationsRestClientService, app.getId(), orgUserId);
1075                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1076                                                         userRolesInLocalApp);
1077                                         logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", 
1078                                                         logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1079                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1080                                 } else {// remote app
1081                                         EPUser remoteAppUser = null;
1082                                         try {
1083                                                 remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
1084                                         } catch (HTTPException e) {
1085                                                 // Some apps are returning 400 if user is not found.
1086                                                 if (e.getResponseCode() == 400) {
1087                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1088                                                                         "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
1089                                                                         e);
1090                                                 } else {
1091                                                         // Other response code, let it come thru.
1092                                                         throw e;
1093                                                 }
1094                                         }
1095                                         if (remoteAppUser == null) {
1096                                                 createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper,
1097                                                                 isAppUpgradeVersion(app));
1098                                                 // If we succeed, we know that the new user was
1099                                                 // persisted on remote app.
1100                                                 remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
1101                                                 if (remoteAppUser == null) {
1102                                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to persist new user: " + orgUserId
1103                                                                         + " in remote app. appId = " + app.getId());
1104                                                         // return null;
1105                                                 }
1106                                                 reqMessage = "Saved Successfully";
1107                                         }
1108                                         if (remoteAppUser != null) {
1109                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1110                                                                                         mapper, applicationsRestClientService, app.getId(), orgUserId); 
1111                                                         
1112                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1113                                                                         app.getId(), userRolesInRemoteApp);
1114                                                         logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", 
1115                                                                         logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1116                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1117                                                         // If no roles remain, request app to set user inactive.
1118                                                         /*if (userRolesInRemoteApp.size() == 0) {
1119                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1120                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1121                                                                                 attuid);
1122                                                                 //TODO Need  to fix the logged in user is not set to inactive
1123                                                                 remoteAppUser.setActive(false);
1124                                                                 postUserToRemoteApp(attuid, user, app, applicationsRestClientService);
1125                                                         }*/
1126
1127                                         }
1128                                         if(!result){
1129                                                 reqMessage = "Failed to save the user app role(s)";
1130                                         }
1131                                         if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1132                                                 updateStatus = "C";
1133                                                 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1134                                         }
1135                                         
1136                                 }
1137                         } catch (Exception e) {
1138                                 String message = String.format("Failed to create user or update user roles for User %s, AppId %s",
1139                                                 orgUserId, appName);
1140                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1141                                 result = false;
1142                                 reqMessage = e.getMessage();
1143                                  if(epRequestIdSize > 0 && !userInfo.isEmpty()){
1144                                  updateStatus = "F";
1145                                  applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1146                                  updateStatus, epRequestId.get(0));
1147                                  }
1148                         }
1149
1150                 }
1151                 return new ExternalRequestFieldsValidator(result, reqMessage);
1152         }
1153         
1154         /**
1155          * 
1156          * @param roleInAppForUserList
1157          * @param mapper
1158          * @param applicationsRestClientService
1159          * @param appId
1160          * @param userId
1161          * @return  Set<EcompRole>
1162          * @throws JsonProcessingException
1163          * @throws HTTPException
1164          */
1165         private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1166                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1167                         throws JsonProcessingException, HTTPException {
1168                 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1169                 return updatedUserRoles;
1170         }
1171         
1172         /**
1173          * It constructs and returns list of user app roles when the external API role approval system calls
1174          * this method
1175          * 
1176          * @param roleInAppForUserList
1177          * @param appId
1178          * @return list of user app roles
1179          * @throws Exception
1180          *                 throws exceptions if role id does not exits 
1181          */
1182         private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1183                         Long appId, String appName) throws Exception {
1184                 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1185                 EPRole existingAppRole = null;
1186                 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1187                         RoleInAppForUser ecompRole = new RoleInAppForUser();
1188                         existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1189                         if (existingAppRole == null) {
1190                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1191                                                 roleInAppForUserList);
1192                                 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for" + appName + " application");
1193                         }
1194                         if (!existingAppRole.getActive()) {
1195                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1196                                                 roleInAppForUserList);
1197                                 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1198                         } else {
1199                                 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1200                                 ecompRole.roleName = roleInAppForUser.getRoleName();
1201                                 ecompRole.isApplied = true;
1202                                 existingUserRoles.add(ecompRole);
1203                         }
1204                 }
1205                 return existingUserRoles;
1206         }
1207         
1208         
1209
1210         /**
1211          * 
1212          * @param userId
1213          * @param app
1214          * @param applicationsRestClientService
1215          * @return EPUser
1216          * @throws HTTPException
1217          */
1218         protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1219                         throws HTTPException {
1220                 // local app
1221                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1222                         // Map<String,String> params = new HashMap<String,String>();
1223                         // params.put("sbcid",userId);
1224                         @SuppressWarnings("unchecked")
1225                         List<EPUser> userList = (List<EPUser>) dataAccessService
1226                                         .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1227                         if (userList != null && !userList.isEmpty())
1228                                 return userList.get(0);
1229                         else
1230                                 return null;
1231                 }
1232                 // remote app
1233                 
1234                 return getUser(userId, app, applicationsRestClientService);
1235         }
1236         
1237         protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1238                         throws HTTPException {
1239                 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1240
1241         }
1242         
1243         protected boolean isAppUpgradeVersion(EPApp app){
1244                 return true;
1245         }
1246         
1247         
1248         public ExternalSystemAccess getExternalRequestAccess(){
1249                 ExternalSystemAccess res = null; 
1250                 try {
1251                         res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1252                                         Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1253                 } catch (Exception e) {
1254                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1255                 }
1256                 return res;             
1257         }
1258         
1259         /*
1260          * (non-Javadoc)
1261          * 
1262          * @see org.openecomp.portalapp.portal.service.UserRolesService#
1263          * getAppRolesForUser(java.lang.Long, java.lang.String)
1264          */
1265         public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1266
1267                 List<RoleInAppForUser> rolesInAppForUser = null;
1268                 try {
1269
1270                         // for ecomp portal app, no need to make a remote call
1271                         if (appId == PortalConstants.PORTAL_APP_ID) {
1272
1273                                 List<Role> roleList = roleService.getAvailableRoles();
1274                                 List<Role> activeRoleList = new ArrayList<Role>();
1275                                 for(Role role: roleList) {
1276                                         if(role.getActive()) {
1277                                                 if(role.getId() != 1){ // prevent portal admin from being added
1278                                                         activeRoleList.add(role);
1279                                                 } else if(extRequestValue){
1280                                                         activeRoleList.add(role);
1281                                                 }
1282                                         }
1283                                                 
1284                                 }
1285                                 
1286                                 EPApp app = appsService.getApp(appId);
1287                                 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1288                                 Set<EPRole> roleSet = localUser.getAppEPRoles(app);
1289                                 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSet.toArray(new EPRole[0]), extRequestValue);
1290                                 return rolesInAppForUser;
1291                         }
1292
1293                         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1294
1295                         // Test this error case, for generating an internal Ecomp Portal
1296                         // error
1297                         // EcompRole[] appRoles = null;
1298                         // If there is an exception in the rest client api, then null will
1299                         // be returned.
1300                         if (appRoles != null) {
1301                                 syncAppRoles(sessionFactory, appId, appRoles);
1302                                 EcompRole[] userAppRoles = null;
1303                                 try {
1304                                         try {
1305                                                 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1306                                                                 String.format("/user/%s/roles", userId));
1307                                         } catch (HTTPException e) {
1308                                                 // Some apps are returning 400 if user is not found.
1309                                                 if (e.getResponseCode() == 400) {
1310                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1311                                                                         "getAppRolesForUser caught exception with response code 400; continuing", e);
1312                                                 } else {
1313                                                         // Other response code, let it come thru.
1314                                                         throw e;
1315                                                 }
1316                                         }
1317                                         if (userAppRoles == null) {
1318                                                 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1319                                                         EcompPortalUtils.setExternalAppResponseCode(200);
1320                                                         String message = String.format(
1321                                                                         "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1322                                                                                         + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1323                                                                                         + "Overriding to 200 until framework SDK returns a useful response.",
1324                                                                         Long.toString(appId), userId);
1325                                                         logger.warn(EELFLoggerDelegate.applicationLogger, message);
1326                                                 }
1327                                         }
1328                                         
1329                                          HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1330                                                 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1331                                                 for (int i = 0; i < userAppRoles.length; i++) {
1332                                                         if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1333                                                                 EcompRole role = new EcompRole();
1334                                                                 role.setId(userAppRoles[i].getId());
1335                                                                 role.setName(userAppRoles[i].getName());
1336                                                                 activeRoles.add(role);
1337                                                         }
1338                                                 }
1339                                                 EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1340                                         
1341                                         // If the remote application isn't down we MUST sync user
1342                                         // roles here in case we have this user here!
1343                                         syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1344                                 } catch (Exception e) {
1345                                         // TODO: we may need to check if user exists, maybe remote
1346                                         // app is down.
1347                                         String message = String.format(
1348                                                         "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1349                                                         Long.toString(appId));
1350                                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
1351                                         userAppRoles = new EcompRole[0];
1352                                 }
1353                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1354                         }
1355                 } catch (Exception e) {
1356                         String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1357                                         Long.toString(appId));
1358                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
1359                 }
1360                 return rolesInAppForUser;
1361
1362         }
1363         
1364         private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1365                         ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1366                         throws JsonProcessingException, HTTPException {
1367                 boolean result = false;
1368                 ObjectMapper mapper = new ObjectMapper();
1369                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1370                 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1371                 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1372                 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1373                 return result;
1374         }
1375
1376         public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1377                 FieldsValidator fieldsValidator = new FieldsValidator();
1378                 final Map<String, Long> params = new HashMap<>();
1379                 EpUserAppRoles  appRole= new EpUserAppRoles();
1380                 try {
1381                         logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1382                         boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1383                         
1384                         params.put("appId", userAppRolesData.appId);
1385                         EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1386                         epAppRolesRequestData.setCreatedDate(new Date());
1387                         epAppRolesRequestData.setUpdatedDate(new Date());
1388                         epAppRolesRequestData.setUserId(user.getId());
1389                         epAppRolesRequestData.setAppId(userAppRolesData.appId);
1390                         epAppRolesRequestData.setRequestStatus("P");
1391                         List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1392                         Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1393                         dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1394                         for (RoleInAppForUser userAppRoles : appRoleIdList) {
1395                                 Boolean isAppliedVal = userAppRoles.isApplied;
1396                                 params.put("appRoleId", userAppRoles.roleId);                           
1397                                 if (isAppliedVal) {
1398                                         appRole = (EpUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
1399                                         EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1400                                         epAppRoleDetail.setReqRoleId(appRole.getRoleId());
1401                                         epAppRoleDetail.setReqType("P");
1402                                         epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1403                                         dataAccessService.saveDomainObject(epAppRoleDetail, null);
1404                                         }                       
1405                         }
1406                         epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1407                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1408
1409                 } catch (Exception e) {
1410                         logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1411                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1412                 }
1413                 return fieldsValidator;
1414         }
1415
1416         public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {      
1417                 Map<String, String> params = new HashMap<>();
1418                 params.put("userid", userid.getId().toString());
1419                 //params.put("appid", appid);
1420                 params.put("appName", appName);
1421                         
1422                 @SuppressWarnings("unchecked")
1423                 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1424                                 .executeNamedQuery("userAppCatalogRoles", params, null);
1425                 return userAppRoles;    
1426         }
1427         
1428         public String updateRemoteUserProfile(String orgUserId, Long appId) {
1429                 ObjectMapper mapper = new ObjectMapper();
1430                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1431                 EPUser client = searchService.searchUserByUserId(orgUserId);
1432                 EPUser newUser = new EPUser();
1433                 newUser.setActive(client.getActive());
1434                 newUser.setFirstName(client.getFirstName());
1435                 newUser.setLastName(client.getLastName());
1436                 newUser.setLoginId(client.getLoginId());
1437                 newUser.setLoginPwd(client.getLoginPwd());
1438                 newUser.setMiddleInitial(client.getMiddleInitial());
1439                 newUser.setEmail(client.getEmail());
1440                 newUser.setOrgUserId(client.getLoginId());
1441                 try {
1442                         String userAsString = mapper.writeValueAsString(newUser);
1443                         List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1444                         // applicationsRestClientService.post(EPUser.class, appId,
1445                         // userAsString, String.format("/user", orgUserId));
1446                         for (EPApp eachApp : appList) {
1447                                 try {
1448                                         applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1449                                                         String.format("/user/%s", orgUserId));
1450                                 } catch (Exception e) {
1451                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1452                                                         + " in remote app. appId = " + eachApp.getId());
1453                                 }
1454                         }
1455                 } catch (Exception e) {
1456                         logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1457                         return "failure";
1458                 }
1459
1460                 return "success";
1461         }
1462
1463
1464         /*
1465          * (non-Javadoc)
1466          * 
1467          * @see org.openecomp.portalapp.portal.service.UserRolesService#
1468          * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1469          */
1470         public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1471                 // Find the records for this user-app combo, if any
1472                 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1473                 @SuppressWarnings("unchecked")
1474                 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1475                 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
1476                 return roleList;
1477         }
1478
1479 }