Repair search and timeout defects
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / UserRolesCommonServiceImpl.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20
21 package org.openecomp.portalapp.portal.service;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.LinkedHashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.TreeSet;
34 import java.util.stream.Collectors;
35
36 import javax.servlet.http.HttpServletResponse;
37
38 import org.apache.commons.lang.StringUtils;
39 import org.apache.cxf.transport.http.HTTPException;
40 import org.hibernate.SQLQuery;
41 import org.hibernate.Session;
42 import org.hibernate.SessionFactory;
43 import org.hibernate.Transaction;
44 import org.json.JSONArray;
45 import org.json.JSONObject;
46 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
47 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser;
48 import org.openecomp.portalapp.portal.domain.EPApp;
49 import org.openecomp.portalapp.portal.domain.EPRole;
50 import org.openecomp.portalapp.portal.domain.EPUser;
51 import org.openecomp.portalapp.portal.domain.EPUserApp;
52 import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles;
53 import org.openecomp.portalapp.portal.domain.EPUserAppRoles;
54 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest;
55 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail;
56 import org.openecomp.portalapp.portal.domain.ExternalSystemAccess;
57 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
58 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
59 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
60 import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
61 import org.openecomp.portalapp.portal.transport.EPUserAppCurrentRoles;
62 import org.openecomp.portalapp.portal.transport.EcompUserAppRoles;
63 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
64 import org.openecomp.portalapp.portal.transport.ExternalAccessUserRoleDetail;
65 import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator;
66 import org.openecomp.portalapp.portal.transport.ExternalRoleDescription;
67 import org.openecomp.portalapp.portal.transport.FieldsValidator;
68 import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
69 import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
70 import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles;
71 import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
72 import org.openecomp.portalapp.portal.transport.RolesInAppForUser;
73 import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
74 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
75 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
76 import org.openecomp.portalapp.portal.utils.PortalConstants;
77 import org.openecomp.portalsdk.core.domain.Role;
78 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
79 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
80 import org.openecomp.portalsdk.core.service.DataAccessService;
81 import org.openecomp.portalsdk.core.service.RoleService;
82 import org.openecomp.portalsdk.core.util.SystemProperties;
83 import org.springframework.beans.factory.annotation.Autowired;
84 import org.springframework.http.HttpEntity;
85 import org.springframework.http.HttpHeaders;
86 import org.springframework.http.HttpMethod;
87 import org.springframework.http.ResponseEntity;
88 import org.springframework.web.client.RestTemplate;
89
90 import com.fasterxml.jackson.core.JsonProcessingException;
91 import com.fasterxml.jackson.databind.DeserializationFeature;
92 import com.fasterxml.jackson.databind.ObjectMapper;
93
94 @EPMetricsLog
95 public class UserRolesCommonServiceImpl  {
96
97         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
98
99         private static final Object syncRests = new Object();
100         
101         @Autowired
102         private DataAccessService dataAccessService;                            
103         @Autowired
104         private SessionFactory sessionFactory;
105         @Autowired
106         private SearchService searchService;
107         @Autowired
108         private EPAppService appsService;
109         @Autowired
110         private ApplicationsRestClientService applicationsRestClientService;
111         @Autowired
112         private EPRoleService epRoleService;
113         @Autowired
114         private RoleService roleService;        
115         
116         @Autowired
117         private ExternalAccessRolesService externalAccessRolesService;
118         
119         RestTemplate template = new RestTemplate();
120         
121         /**
122          * 
123          * @param ecompRoles
124          * @return  HashMap<Long, EcompRole>
125          */
126         private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
127                 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
128                 if (ecompRoles != null) {
129                         for (int i = 0; i < ecompRoles.length; i++) {
130                                 if (ecompRoles[i].getId() != null) {
131                                         result.put(ecompRoles[i].getId(), ecompRoles[i]);
132                                 }
133                         }
134                 }
135                 return result;
136         }
137         
138         /**
139          * 
140          * @param userId
141          */
142         protected void createLocalUserIfNecessary(String userId) {
143                 if (StringUtils.isEmpty(userId)) {
144                         logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
145                         return;
146                 }
147                 Session localSession = null;
148                 Transaction transaction = null;
149                 try {
150                         localSession = sessionFactory.openSession();
151                         transaction = localSession.beginTransaction();
152                         @SuppressWarnings("unchecked")
153                         List<EPUser> userList = localSession
154                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
155                         if (userList.size() == 0) {
156                                 EPUser client = searchService.searchUserByUserId(userId);
157                                 if (client == null) {
158                                         String msg = "createLocalUserIfNecessary: cannot create user " + userId
159                                                         + ", because not found in phonebook";
160                                         logger.error(EELFLoggerDelegate.errorLogger, msg);
161                                 } else {
162                                         client.setLoginId(userId);
163                                         client.setActive(true);
164                                         localSession.save(client);
165                                 }
166                         }
167                         transaction.commit();
168                 } catch (Exception e) {
169                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
170                         EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
171                 } finally {
172                         EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
173                 }
174         }
175         
176         /**
177          * This method return nothing and remove roles before adding any roles for an app
178          * @param userRole
179          * @param appId
180          * @param localSession
181          * @param userAppRoles
182          * @param newUserAppRolesMap
183          */
184         private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
185
186                 Long userAppRoleId = 0L;
187                 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
188                         userAppRoleId = userRole.getRoleId();
189                 } else { // remote app
190                         userAppRoleId = userRole.getAppRoleId();
191                 }
192
193                 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
194                         localSession.delete(userRole);
195                 } else {
196                         newUserAppRolesMap.remove(userAppRoleId);
197                 }
198         }
199         
200         /**
201          * Checks whether the role is inactive
202          *  
203          * @param epRole
204          * @throws Exception
205          *                      if role is inactive, throws exception
206          */
207         private void checkIfRoleInactive(EPRole epRole) throws Exception{       
208                 if(!epRole.getActive()){
209                         throw new Exception(epRole.getName()+ " role is unavailable");
210                 }
211         }
212         
213         /**
214          * 
215          * @param sessionFactory
216          * @param userId
217          * @param appId
218          * @param userAppRoles
219          * @param extRequestValue 
220          *                      set to false if request is from users page otherwise true
221          * @throws Exception
222          */
223         protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
224                         EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
225                 boolean result = false;
226                 Session localSession = null;
227                 Transaction transaction = null;
228                 String roleActive = null;
229                 final Map<String, String> userAppParams = new HashMap<>();
230                 final Map<String, String> appParams = new HashMap<>();
231                 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
232
233                 try {
234                         localSession = sessionFactory.openSession();
235                         transaction = localSession.beginTransaction();
236                         @SuppressWarnings("unchecked")
237                         List<EPUser> userList = localSession
238                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
239                         if (userList.size() > 0) {
240                                 EPUser client = userList.get(0);
241                                 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
242                                 @SuppressWarnings("unchecked")
243                                 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
244                                                 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
245                                 
246                                 if ("DELETE".equals(reqType)) {
247                                         for (EPUserApp userAppRoleList : userRoles) {
248                                                 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
249                                                 userAppParams.put("appId",  String.valueOf(appId));
250                                                 appParams.put("appRoleName", userAppRoleList.getRole().getName());
251                                                 @SuppressWarnings("unchecked")
252                                                 List<EPRole>  rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);        
253                                                 if(rolesList.size() > 0 || !rolesList.isEmpty()){
254                                                 checkIfRoleInactive(rolesList.get(0));
255                                                 }
256                                         }
257                                 }
258
259                                 for (EPUserApp userRole : userRoles) {
260                                         if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
261                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
262                                                 }
263                                         else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
264                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
265                                         }
266                                         else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
267                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
268                                         }
269                                 }
270                                 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
271                                 if (newRolesToAdd.size() > 0) {
272                                         EPApp app = (EPApp) localSession.get(EPApp.class, appId);
273
274                                         HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
275                                         if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
276                                                 String appIdValue = "";
277                                                 if(!extRequestValue){
278                                                         appIdValue = "and id != " +  PortalConstants.SYS_ADMIN_ROLE_ID; 
279                                                 }
280                                                 @SuppressWarnings("unchecked")
281                                                 List<EPRole> roles = localSession
282                                                                 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
283                                                 for (EPRole role : roles) {
284                                                         role.setAppId(1L);
285                                                         rolesMap.put(role.getId(), role);
286                                                 }
287                                         } else { // remote app
288                                                 @SuppressWarnings("unchecked")
289                                                 List<EPRole> roles = localSession
290                                                                 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
291                                                 for (EPRole role : roles) {
292                                                         if (!extRequestValue && app.getCentralAuth()) {
293                                                                 rolesMap.put(role.getId(), role);
294                                                         } else {
295                                                                 rolesMap.put(role.getAppRoleId(), role);
296                                                         }
297                                                 }
298                                         }
299
300                                         EPRole role = null;
301                                         for (EcompRole userRole : newRolesToAdd) {
302                                                 EPUserApp userApp = new EPUserApp();
303                                                 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
304                                                         role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
305                                                         userApp.setRole(role);
306                                                 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
307                                                                 continue;
308                                                 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
309                                                         continue;
310                                                 }                                               
311                                                 else {
312                                                         userApp.setRole(rolesMap.get(userRole.getId()));
313                                                 }
314
315                                                 userApp.setUserId(client.getId());
316                                                 userApp.setApp(app);
317                                                 localSession.save(userApp);
318                                                 localSession.flush();
319                                         }
320
321                                         if (appId == PortalConstants.PORTAL_APP_ID) {
322                                                 /*
323                                                  * for local app -- hack - always make sure fn_role
324                                                  * table's app_id is null and not 1 for primary app in
325                                                  * this case being ecomp portal app; reason: hibernate
326                                                  * is rightly setting this to 1 while persisting to
327                                                  * fn_role as per the mapping but SDK role management
328                                                  * code expects the app_id to be null as there is no
329                                                  * concept of App_id in SDK
330                                                  */
331                                                 localSession.flush();
332                                                 SQLQuery sqlQuery = localSession
333                                                                 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
334                                                 sqlQuery.executeUpdate();
335                                                 
336                                         }
337                                 }
338                         }
339                         transaction.commit();
340                         result = true;
341                 } catch (Exception e) {
342                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
343                         EcompPortalUtils.rollbackTransaction(transaction,
344                                         "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e));
345                         if("DELETE".equals(reqType)){
346                                 throw new Exception(e.getMessage());
347                         }
348                 } finally {
349                         localSession.close();
350                         if (!result && !"DELETE".equals(reqType)) {
351                                 throw new Exception(
352                                                 "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
353                         }
354                 }
355         }
356         
357         /**
358          * Called when getting the list of roles for the user
359          * 
360          * @param appRoles
361          * @param userAppRoles
362          * @return List<RoleInAppForUser> 
363          */
364         protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
365                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
366
367                 Set<Long> userAppRolesMap = new HashSet<Long>();
368                 if (userAppRoles != null) {
369                         for (EcompRole ecompRole : userAppRoles) {
370                                 userAppRolesMap.add(ecompRole.getId());
371                         }
372                 } else {
373                         logger.error(EELFLoggerDelegate.errorLogger,
374                                         "constructRolesInAppForUserGet has received userAppRoles list empty");
375                 }
376
377                 if (appRoles != null) {
378                         for (EcompRole ecompRole : appRoles) {
379                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
380                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
381                                 rolesInAppForUser.add(roleForUser);
382                         }
383                 } else {
384                         logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
385                 }
386                 return rolesInAppForUser;
387         }
388
389         /**
390          * Called when getting the list of roles for the user
391          * 
392          * @param appRoles
393          * @param userAppRoles
394          * @param extRequestValue 
395          *                      set to false if request is from users page otherwise true
396          * @return List<RoleInAppForUser>
397          */
398         protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
399                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
400
401                 Set<Long> userAppRolesMap = new HashSet<Long>();
402                 if (userAppRoles != null) {
403                         for (EPRole ecompRole : userAppRoles) {
404                                 userAppRolesMap.add(ecompRole.getId());
405                         }
406                 } else {
407                         logger.error(EELFLoggerDelegate.errorLogger,
408                                         "constructRolesInAppForUserGet has received userAppRoles list empty.");
409                 }
410
411                 if (appRoles != null) {
412                         for (Role ecompRole : appRoles) {
413                                 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
414                                         continue;
415                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
416                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
417                                 rolesInAppForUser.add(roleForUser);
418                         }
419                 } else {
420                         logger.error(EELFLoggerDelegate.errorLogger,
421                                         "constructRolesInAppForUser has received appRoles list empty.");
422                 }
423                 return rolesInAppForUser;
424         }
425
426         
427         /**
428          * copies of methods in GetAppsWithUserRoleState
429          * 
430          * @param sessionFactory
431          * @param appId
432          * @param appRoles
433          * @throws Exception
434          */
435         protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
436                 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
437                 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
438                 Session localSession = null;
439                 Transaction transaction = null;
440
441                 try {
442                         localSession = sessionFactory.openSession();
443                         transaction = localSession.beginTransaction();
444                         // Attention! All roles from remote application supposed to be
445                         // active!
446                         @SuppressWarnings("unchecked")
447                         List<EPRole> currentAppRoles = localSession
448                                         .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
449                         List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
450                         for (int i = 0; i < currentAppRoles.size(); i++) {
451                                 EPRole oldAppRole = currentAppRoles.get(i);
452                                 if (oldAppRole.getAppRoleId() != null) {
453                                         EcompRole role = null;
454                                         role = newRolesMap.get(oldAppRole.getAppRoleId());
455                                         if (role != null) {
456                                                 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
457                                                         oldAppRole.setName(role.getName());
458                                                         localSession.update(oldAppRole);
459                                                 }
460                                                 newRolesMap.remove(oldAppRole.getAppRoleId());
461                                         } else {
462                                                 obsoleteRoles.add(oldAppRole);
463                                         }
464                                 } else {
465                                         obsoleteRoles.add(oldAppRole);
466                                 }
467                         }
468                         Collection<EcompRole> newRolesToAdd = newRolesMap.values();
469                         if (obsoleteRoles.size() > 0) {
470                                 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
471                                 for (EPRole role : obsoleteRoles) {
472                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
473                                         Long roleId = role.getId();
474                                         // delete obsolete roles here
475                                         // Must delete all records with foreign key constraints on
476                                         // fn_role:
477                                         // fn_user_role, fn_role_composite, fn_role_function,
478                                         // fn_user_pseudo_role, fn_menu_functional_roles.
479                                         // And for fn_menu_functional, if no other roles for that
480                                         // menu item, remove the url.
481
482                                         // Delete from fn_user_role
483                                         @SuppressWarnings("unchecked")
484                                         List<EPUserApp> userRoles = localSession.createQuery(
485                                                         "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
486                                                         .list();
487
488                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
489                                         for (EPUserApp userRole : userRoles) {
490                                                 logger.debug(EELFLoggerDelegate.debugLogger,
491                                                                 "syncAppRoles: about to delete userRole: " + userRole.toString());
492                                                 localSession.delete(userRole);
493                                                 logger.debug(EELFLoggerDelegate.debugLogger,
494                                                                 "syncAppRoles: finished deleting userRole: " + userRole.toString());
495                                         }
496
497                                         // Delete from fn_menu_functional_roles
498                                         @SuppressWarnings("unchecked")
499                                         List<FunctionalMenuRole> funcMenuRoles = localSession
500                                                         .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
501                                                         .list();
502                                         int numMenuRoles = funcMenuRoles.size();
503                                         logger.debug(EELFLoggerDelegate.debugLogger,
504                                                         "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
505                                         for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
506                                                 Long menuId = funcMenuRole.menuId;
507                                                 // If this is the only role for this menu item, then the
508                                                 // app and roles will be gone,
509                                                 // so must null out the url too, to be consistent
510                                                 @SuppressWarnings("unchecked")
511                                                 List<FunctionalMenuRole> funcMenuRoles2 = localSession
512                                                                 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
513                                                                 .list();
514                                                 int numMenuRoles2 = funcMenuRoles2.size();
515                                                 logger.debug(EELFLoggerDelegate.debugLogger,
516                                                                 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
517                                                 localSession.delete(funcMenuRole);
518                                                 if (numMenuRoles2 == 1) {
519                                                         // If this is the only role for this menu item, then
520                                                         // the app and roles will be gone,
521                                                         // so must null out the url too, to be consistent
522                                                         logger.debug(EELFLoggerDelegate.debugLogger,
523                                                                         "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
524                                                         @SuppressWarnings("unchecked")
525                                                         List<FunctionalMenuItem> funcMenuItems = localSession
526                                                                         .createQuery(
527                                                                                         "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
528                                                                         .list();
529                                                         if (funcMenuItems.size() > 0) {
530                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
531                                                                 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
532                                                                 funcMenuItem.url = "";
533                                                                 localSession.update(funcMenuItem);
534                                                         }
535                                                 }
536                                         }
537                                         externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId);
538                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
539                                         localSession.delete(role);
540                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
541                                 }
542                         }
543                         for (EcompRole role : newRolesToAdd) {
544                                 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
545                                 EPRole newRole = new EPRole();
546                                 // Attention! All roles from remote application supposed to be
547                                 // active!
548                                 newRole.setActive(true);
549                                 newRole.setName(role.getName());
550                                 newRole.setAppId(appId);
551                                 newRole.setAppRoleId(role.getId());
552                                 localSession.save(newRole);
553                         }
554                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
555                         transaction.commit();
556                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
557                 } catch (Exception e) {
558                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
559                         EcompPortalUtils.rollbackTransaction(transaction,
560                                         "syncAppRoles: Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e));
561                         throw new Exception(e);
562                 } finally {
563                         localSession.close();
564                 }
565         }
566         
567         
568         
569         
570         
571         /**
572          * Called when updating the list of roles for the user
573          * 
574          * @param userId
575          * @param appId
576          * @param userRolesInRemoteApp
577          * @return RolesInAppForUser
578          */
579         protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
580                         Set<EcompRole> userRolesInRemoteApp) {
581                 RolesInAppForUser result;
582                 result = new RolesInAppForUser();
583                 result.appId = appId;
584                 result.orgUserId = userId;
585                 for (EcompRole role : userRolesInRemoteApp) {
586                         RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
587                         roleInAppForUser.roleId = role.getId();
588                         roleInAppForUser.roleName = role.getName();
589                         roleInAppForUser.isApplied = new Boolean(true);
590                         result.roles.add(roleInAppForUser);
591                 }
592                 return result;
593         }
594         
595         /**
596          * 
597          * @param roleInAppForUserList
598          * @return boolean
599          */
600         protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
601                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
602                         if (roleInAppForUser.isApplied.booleanValue()) {
603                                 return true;
604                         }
605                 }
606                 return false;
607         }
608         
609         /**
610          * Builds JSON and posts it to a remote application to update user roles.
611          * 
612          * @param roleInAppForUserList
613          * @param mapper
614          * @param applicationsRestClientService
615          * @param appId
616          * @param userId
617          * @return Set of roles as sent; NOT the response from the app.
618          * @throws JsonProcessingException
619          * @throws HTTPException
620          */
621         protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
622                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
623                         throws JsonProcessingException, HTTPException {
624                 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
625                 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
626                 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
627                 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
628                                 String.format("/user/%s/roles", userId));
629                 // TODO: We should add code that verifies that the post operation did
630                 // succeed. Because the SDK may still return 200 OK with an html page
631                 // even when it fails!
632                 return updateUserRolesInEcomp;
633         }
634         
635         /**
636          * 
637          * @param roleInAppForUserList
638          * @return Set<EcompRole> 
639          */
640         protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
641                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
642                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
643                         if (roleInAppForUser.isApplied) {
644                                 EcompRole ecompRole = new EcompRole();
645                                 ecompRole.setId(roleInAppForUser.roleId);
646                                 ecompRole.setName(roleInAppForUser.roleName);
647                                 existingUserRoles.add(ecompRole);
648                         }
649                 }
650                 return existingUserRoles;
651         }
652         
653         /**
654          * Constructs user app roles excluding Account Administrator role
655          * 
656          * @param roleInAppForUserList
657          * @return
658          *            List of roles with Role name, Role Id
659          */
660         protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
661                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
662                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
663                         if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
664                                 EcompRole ecompRole = new EcompRole();
665                                 ecompRole.setId(roleInAppForUser.roleId);
666                                 ecompRole.setName(roleInAppForUser.roleName);
667                                 existingUserRoles.add(ecompRole);
668                         }
669                 }
670                 return existingUserRoles;
671         }
672         
673         /**
674          * This is for a single app
675          * 
676          * @param rolesInAppForUser
677          * @param externalSystemRequest  
678          *                      set to false if requests from Users page otherwise true
679          * @return true on success, false otherwise
680          */
681         protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
682                 boolean result = false;
683                 String userId = rolesInAppForUser.orgUserId;
684                 Long appId = rolesInAppForUser.appId;
685                 synchronized (syncRests) {
686                         if (rolesInAppForUser != null) {
687                                 createLocalUserIfNecessary(userId);
688                         }
689
690                         if (rolesInAppForUser != null) {
691                                 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
692                                 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
693                                         RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
694                                         EcompRole role = new EcompRole();
695                                         role.setId(roleInAppForUser.roleId);
696                                         role.setName(roleInAppForUser.roleName);
697                                         userAppRoles[i] = role;
698                                 }
699                                 try {
700                                         syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
701                                         result = true;
702                                 } catch (Exception e) {
703                                         logger.error(EELFLoggerDelegate.errorLogger,
704                                                         "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
705                                         if("DELETE".equals(reqType)){
706                                                 throw new Exception(e.getMessage());
707                                         }
708                                 }
709                         }
710                 }
711                 return result;
712         }
713         
714         /**
715          * 
716          * @param appId
717          * @param remoteUser
718          * @return UserApplicationRoles
719          */
720         protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
721                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
722                 userWithRemoteAppRoles.setAppId(appId);
723                 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
724                 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
725                 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
726                 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
727                 return userWithRemoteAppRoles;
728         }
729         
730         /*
731          * (non-Javadoc)
732          * 
733          * @see org.openecomp.portalapp.portal.service.UserRolesService#
734          * importRolesFromRemoteApplication(java.lang.Long)
735          */
736         public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
737                 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
738                 List<EPRole> rolesList = Arrays.asList(appRolesFull);
739                 for (EPRole externalAppRole : rolesList) {
740
741                         // Try to find an existing extern role for the app in the local
742                         // ecomp DB. If so, then use its id to update the existing external
743                         // application role record.
744                         Long externAppId = externalAppRole.getId();
745                         EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
746                         if (existingAppRole != null) {
747                                 logger.debug(EELFLoggerDelegate.debugLogger,
748                                                 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
749                                                                 appId, externAppId));
750                                 continue;
751                         }
752                         // persistExternalRoleInEcompDb(externalAppRole, appId,
753                         // roleService);
754                 }
755
756                 return rolesList;
757         }
758         
759         /**
760          * It adds new user for remote application
761          * 
762          * @param roleInAppForUserList
763          * @param remoteAppUser
764          * @param userId
765          * @param app
766          * @param mapper
767          * @param searchService
768          * @param applicationsRestClientService
769          * @return 
770          * @throws Exception
771          */
772         private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
773                 EPUser addRemoteUser = null;
774                 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
775                         
776                         createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
777                         // If we succeed, we know that the new user was
778                         // persisted on remote app.
779                         addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
780                         if (addRemoteUser == null) {
781                                 logger.error(EELFLoggerDelegate.errorLogger,
782                                                 "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId());
783                                 // return null;
784                         }
785                 }
786                 return addRemoteUser;
787         }
788         
789         /**
790          * It checks whether the remote user exists or not
791          * if exits returns user object else null
792          * 
793          * @param userId
794          * @param app
795          * @param applicationsRestClientService
796          * @return
797          * @throws HTTPException
798          */
799         private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
800                 EPUser checkRemoteUser = null;
801                 try {
802                         checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
803                 } catch (HTTPException e) {
804                         // Some apps are returning 400 if user is not found.
805                         if (e.getResponseCode() == 400) {
806                                 logger.debug(EELFLoggerDelegate.debugLogger,
807                                                 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
808                                                 e);
809                         } else if(e.getResponseCode() == 404) {
810                                 logger.debug(EELFLoggerDelegate.debugLogger,
811                                                 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
812                                                 e);
813                         } else {
814                                 // Other response code, let it come thru.
815                                 throw e;
816                         }
817                 }
818                 return checkRemoteUser;
819         }
820         
821         
822         /*
823          * (non-Javadoc)
824          * 
825          * @see org.openecomp.portalapp.portal.service.UserRolesService#
826          * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
827          * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
828          */
829         public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
830                 boolean result = false;
831                 boolean epRequestValue = false;
832                 String userId = "";
833                 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
834                         userId = newAppRolesForUser.orgUserId.trim();
835                 }
836                 Long appId = newAppRolesForUser.appId;
837                 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
838                 if (userId.length() > 0) {
839                         ObjectMapper mapper = new ObjectMapper();
840                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
841
842                         try {
843                                 EPApp app = appsService.getApp(appId);
844                                 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
845
846                                 // if centralized app
847                                 if (app.getCentralAuth()) {
848                                         // We should add If user does not exist in remote application
849                                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
850                                                 EPUser remoteAppUser = null;
851                                                 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
852
853                                                 if (remoteAppUser == null) {
854                                                         addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
855                                                                         applicationsRestClientService);
856                                                 }
857                                         }
858                                         
859                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
860                                                         applicationsRestClientService, appId, userId);
861                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
862                                                         userRolesInLocalApp);
863                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
864                                         // Apply changes in external Access system
865                                         updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, epRequestValue);
866                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
867                                 } 
868                                 // In case if portal is not centralized then follow existing approach
869                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
870                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
871                                                         applicationsRestClientService, appId, userId);  
872                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
873                                                         userRolesInLocalApp);
874                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
875                                 } else{// remote app
876                                         EPUser remoteAppUser = null;
877                                         if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
878                                                 
879                                                 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
880                 
881                                                 if (remoteAppUser == null) {
882                                                         remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
883                                                 }
884                                                 if (remoteAppUser != null) {
885                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
886                                                                         applicationsRestClientService, appId, userId);
887                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
888                                                                         userRolesInRemoteApp);
889                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
890
891                                                         // If no roles remain, request app to set user inactive.
892                                                         if (userRolesInRemoteApp.size() == 0) {
893                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
894                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
895                                                                                 userId);
896                                                                 remoteAppUser.setActive(false);
897                                                                 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
898                                                         }
899                                                 }
900                                         }
901                                 }
902                         } catch (Exception e) {
903                                 String message = String.format(
904                                                 "Failed to create user or update user roles for User %s, AppId %s",
905                                                 userId, Long.toString(appId));
906                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
907                                 result = false;
908                         }
909
910                 }
911                 return result;
912         }
913         /**
914          * It adds user roles in External system and also make data consistent in both local and in External System 
915          * 
916          * @param app details
917          * @param orgUserId
918          * @param roleInAppUser Contains list of active roles 
919          */
920         @SuppressWarnings("unchecked")
921         private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest)
922         {
923                 try {
924                         // check if user exists
925                         final Map<String, String> userParams = new HashMap<>();
926                         userParams.put("orgUserIdValue", orgUserId);
927                         List<EPUser> userInfo = checkIfUserExists(userParams);
928                         if (userInfo.isEmpty()) {
929                                 createLocalUserIfNecessary(orgUserId);
930                         }
931                         String name = "";
932                         if (EPCommonSystemProperties
933                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
934                                 name = orgUserId
935                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
936                         }
937                         ObjectMapper mapper = new ObjectMapper();
938                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
939                         HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
940                         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
941                         ResponseEntity<String> getResponse = template
942                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
943                                                         + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
944                         if (getResponse.getStatusCode().value() == 200) {
945                                 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}",
946                                                 getResponse.getBody());
947
948                         }
949                         List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
950                         String res = getResponse.getBody();
951                         JSONObject jsonObj = null;
952                         JSONArray extRoles = null;
953                         if (!res.equals("{}")) {
954                                 jsonObj = new JSONObject(res);
955                                 extRoles = jsonObj.getJSONArray("role");
956                         }
957                         ExternalAccessUserRoleDetail userRoleDetail = null;
958                         if (extRoles != null) {
959                                 for (int i = 0; i < extRoles.length(); i++) {
960                                         if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
961                                                         && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
962                                                         && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
963                                                 ObjectMapper descMapper = new ObjectMapper();
964                                                 if (extRoles.getJSONObject(i).has("description")) {
965                                                         ExternalRoleDescription desc = descMapper.readValue(
966                                                                         extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
967                                                         userRoleDetail = new ExternalAccessUserRoleDetail(
968                                                                         extRoles.getJSONObject(i).getString("name"), desc);
969                                                         userRoleDetailList.add(userRoleDetail);
970                                                 } else {
971                                                         userRoleDetail = new ExternalAccessUserRoleDetail(
972                                                                         extRoles.getJSONObject(i).getString("name"), null);
973                                                         userRoleDetailList.add(userRoleDetail);
974                                                 }
975
976                                         }
977                                 }
978                         }
979                         // If request coming from portal not from external role approval system then we have to check if user already 
980                         // have account admin or system admin as GUI will not send these roles 
981                         if (!isPortalRequest) {
982                                 final Map<String, String> loginIdParams = new HashMap<>();
983                                 loginIdParams.put("orgUserIdValue", orgUserId);
984                                 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
985                                 final Map<String, Long> params = new HashMap<>();
986                                 params.put("appId", app.getId());
987                                 params.put("userId", user.getId());
988                                 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
989                                                 params, null);
990                                 if (!roleInAppUser.isEmpty()) {
991                                         for (EcompUserAppRoles userApp : userAppList) {
992                                                 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
993                                                                 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
994                                                         RoleInAppForUser addSpecialRole = new RoleInAppForUser();
995                                                         addSpecialRole.setIsApplied(true);
996                                                         addSpecialRole.setRoleId(userApp.getRoleId());
997                                                         addSpecialRole.setRoleName(userApp.getRoleName());
998                                                         roleInAppUser.add(addSpecialRole);
999                                                 }
1000                                         }
1001                                 }
1002                         }
1003                         List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1004                                         .collect(Collectors.toList());
1005                         final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1006                         for (RoleInAppForUser roleInAppUserNew : roleInAppUser) {
1007                                 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName(), roleInAppUserNew);
1008                         }
1009                         final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1010                         for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleDetailList) {
1011                                 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1012                         }
1013                         // Check if roles does not exists in local but still there in External Central Auth System delete them all
1014                         for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) {
1015                                 if (!(currentUserRolesToUpdate
1016                                                 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1).replaceAll("_", " "))
1017                                                 || currentUserRolesToUpdate
1018                                                                 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1019                                         HttpEntity<String> entity = new HttpEntity<>(headers);
1020                                         logger.debug(EELFLoggerDelegate.debugLogger,
1021                                                         "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1022                                                         userRole);
1023                                         ResponseEntity<String> deleteResponse = template.exchange(
1024                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1025                                                                         + "userRole/" + name + "/" + userRole.getName(),
1026                                                         HttpMethod.DELETE, entity, String.class);
1027                                         logger.debug(EELFLoggerDelegate.debugLogger,
1028                                                         "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1029                                                         userRole, deleteResponse.getBody());
1030                                 }
1031                         }
1032                         // Check if user roles does not exists in External Central Auth System add them all
1033                         for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1034                                 if (!(currentUserRolesInExternalSystem
1035                                                 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_")))) {
1036                                         ExternalAccessUser extUser = new ExternalAccessUser(name,
1037                                                         app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_"));
1038                                         String formattedUserRole = mapper.writeValueAsString(extUser);
1039                                         HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1040                                         logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system and adding user role",
1041                                                         addUserRole.getRoleName());
1042                                         ResponseEntity<String> addResponse = template
1043                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1044                                                                         + "userRole", HttpMethod.POST, entity, String.class);
1045                                         logger.debug(EELFLoggerDelegate.debugLogger,
1046                                                         "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1047                                                         getResponse.getBody(), addUserRole.getRoleName());
1048                                         if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1049                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1050                                                                 "Finished POST operation in external system but unable to save user role", getResponse.getBody(),
1051                                                                 addUserRole.getRoleName());
1052                                                 throw new Exception(addResponse.getBody());
1053                                         }
1054                                 }
1055                         }
1056                 } catch (Exception e) {
1057                         logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1058                 }
1059
1060         }
1061
1062         /**
1063          * 
1064          * @param userId
1065          * @param app
1066          * @param applicationsRestClientService
1067          * @param searchService
1068          * @param mapper
1069          * @throws Exception
1070          */
1071         protected void createNewUserOnRemoteApp(String userId, EPApp app,
1072                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1073                         ObjectMapper mapper, boolean postOpenSource) throws Exception {
1074
1075                         
1076                         EPUser client = searchService.searchUserByUserId(userId);
1077                         
1078                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1079                         
1080                         if (client == null) {
1081                                 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1082                                 logger.error(EELFLoggerDelegate.errorLogger, msg);
1083                                 throw new Exception(msg);
1084                         }
1085
1086                         client.setLoginId(userId);
1087                         client.setActive(true);
1088
1089                         String userInString = null;
1090                         userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1091                         logger.debug(EELFLoggerDelegate.debugLogger,
1092                                         "about to post new client to remote application, users json = " + userInString);
1093                         applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1094
1095         }
1096         
1097         @SuppressWarnings("unchecked")
1098         protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1099                 final Map<String, Long> epRequestParams = new HashMap<>();
1100                 try {
1101                         EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1102                         epAppRolesRequestData.setUpdatedDate(new Date());
1103                         epAppRolesRequestData.setRequestStatus(updateStatus);
1104                         HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1105                         addiotonalUpdateParam.put("userId", userId);
1106                         dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1107                         epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1108                         List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1109                         epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1110                                         epRequestParams, null);
1111                         if (epUserAppRolessDetailList.size() > 0) {
1112                                 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1113                                         EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1114                                         epAppRoleDetailData.setReqType(updateStatus);
1115                                         epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1116                                         HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1117                                         addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1118                                         dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1119                                 }
1120                         }
1121                         logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1122
1123                 } catch (Exception e) {
1124                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1125                 }
1126         }
1127         
1128         @SuppressWarnings("unchecked")
1129         public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1130                 final Map<String, Long> params = new HashMap<>();
1131                 final Map<String, Long> epDetailParams = new HashMap<>();
1132                 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1133                 params.put("appId", appId);
1134                 params.put("userId", user.getId());
1135                 try {
1136                         epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1137                                         .executeNamedQuery("userAppRolesRequestList", params, null);
1138                         if (epRequestIdVal.size() > 0) {
1139                                 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1140                                 epAppRolesRequestData.setUpdatedDate(new Date());
1141                                 epAppRolesRequestData.setRequestStatus("O");
1142                                 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1143                                 addiotonalUpdateParam.put("userId", user.getId());
1144                                 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1145                                 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1146                                 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1147                                 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1148                                                 epDetailParams, null);
1149                                 if (epUserAppRolesDetailList.size() > 0) {
1150                                         for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1151                                                 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1152                                                 epAppRoleDetailData.setReqType("O");
1153                                                 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1154                                                 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1155                                                 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1156                                                 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1157                                         }
1158                                         logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1159                                 }
1160                         }
1161
1162                 } catch (Exception e) {
1163                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1164                 }
1165         }
1166         
1167         /**
1168          * Pushes specified user details to the specified remote app.
1169          * 
1170          * @param userId
1171          *            OrgUserId identifying user at remote app in REST endpoint path
1172          * @param user
1173          *            User details to be pushed
1174          * @param app
1175          *            Remote app
1176          * @param applicationsRestClientService
1177          * @throws HTTPException
1178          */
1179         protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1180                         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1181         
1182                  getUser(userId, app, applicationsRestClientService);
1183                                         
1184         }
1185         
1186         /**
1187          * It returns user details for single org user id
1188          * 
1189          * @param userParams
1190          * @return
1191          *              if user exists it returns list of user details otherwise empty value
1192          */
1193         @SuppressWarnings("unchecked")
1194         private List<EPUser> checkIfUserExists(Map<String, String> userParams){ 
1195                 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1196         }
1197         
1198         /**
1199          * It checks whether the new user is valid or not otherwise throws exception
1200          * 
1201          * @param orgUserId
1202          * @param app
1203          * @return 
1204          *                      Checks if user is valid and returns message otherwise throws exception
1205          * @throws Exception
1206          */
1207         private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1208                 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1209                 if (epUser == null) {
1210                         throw new Exception("User does not exist");
1211                 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1212                         throw new Exception("User does not exist");
1213                 } else if (app == null) {
1214                         throw new Exception("Application does not exist");
1215                 }
1216                 return "Saved Successfully";
1217         }
1218         
1219         /**
1220          *   Checks if the fields exists or not
1221          *   
1222          * @param userList
1223          *                      contains user information
1224          * @param app
1225          *                      contains app name
1226          * @throws Exception
1227          *                      throws exception if the field is not valid
1228          */
1229         private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1230                 if (userList.size() == 0 || userList.isEmpty() ) {
1231                         throw new Exception("User does not exist");
1232                 } else if(app == null) {
1233                         throw new Exception("Application does not exist");
1234                 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1235                         throw new Exception(app.getMlAppName()+" application is unavailable");
1236                 }
1237         }
1238         
1239         @SuppressWarnings("unchecked")
1240         public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1241                 boolean result = false;
1242                 boolean externalSystemRequest = true;
1243                 final Map<String, Long> params = new HashMap<>();
1244                 final Map<String, String> userParams = new HashMap<>();
1245                 List<EPUser> userInfo = null;
1246                 EPUser userId = null;
1247                 List<EPUserAppRolesRequest> epRequestId = null;
1248                 String orgUserId = "";
1249                 String updateStatus = "";
1250                 String reqMessage = "";
1251                 EPApp app = null;
1252                 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1253                         orgUserId = newAppRolesForUser.getLoginId().trim();
1254                 }
1255                 String appName = newAppRolesForUser.getApplicationName();
1256                 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1257                 if (orgUserId.length() > 0) {
1258                         ObjectMapper mapper = new ObjectMapper();
1259                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1260                         int epRequestIdSize = 0;
1261                         try {
1262                                 app = appsService.getAppDetail(appName);
1263                                 userParams.put("orgUserIdValue", orgUserId);
1264                                 userInfo = checkIfUserExists(userParams);
1265                                 reqMessage = "Updated Successfully";
1266                                 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1267                                         reqMessage = validateNewUser(orgUserId, app);
1268                                 }
1269                                 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1270                                         validateExternalRequestFields(userInfo, app);
1271                                         userId = userInfo.get(0);
1272                                         params.put("appId", app.getId());
1273                                         params.put("userId", userId.getId());
1274                                         epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1275                                                         .executeNamedQuery("userAppRolesRequestList", params, null);
1276                                         epRequestIdSize = epRequestId.size();
1277                                 }
1278                                 
1279                                 //If Non-Centralized app make sure you sync app roles before assigning to user
1280                                 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()){        
1281                                 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1282                                 syncAppRoles(sessionFactory, app.getId(), appRoles);
1283                                 }
1284                                 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1285                                                 app.getId(), app.getMlAppName());
1286                                 List<EcompUserAppRoles> userRoleList = null;
1287                                 if(!userInfo.isEmpty()){
1288                                 final Map<String, Long> appParams = new HashMap<>();
1289                                 appParams.put("userId", userId.getId());
1290                                 appParams.put("appId", app.getId());
1291                                 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1292                                 }
1293                                 // Check if list contains just account admin role
1294                                 boolean checkIfAdminRoleExists = false;
1295                                 if (reqType.equals("DELETE")) {
1296                                         checkIfAdminRoleExists = userRoleList.stream()
1297                                                         .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1298                                 } else {
1299                                         checkIfAdminRoleExists = roleInAppForUserList.stream()
1300                                                         .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1301                                 }
1302                                 // if Centralized app
1303                                 if (app.getCentralAuth()) {
1304                                         // We should add If user does not exist in remote application
1305                                         try {
1306                                                 // If adding just account admin role dont make remote application user call
1307                                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists
1308                                                                 && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) {
1309                                                         EPUser remoteAppUser = null;
1310                                                         remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app,
1311                                                                         applicationsRestClientService);
1312                                                         if (remoteAppUser == null) {
1313                                                                 addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService,
1314                                                                                 applicationsRestClientService);
1315                                                                 reqMessage = "Saved Successfully";
1316                                                         }
1317                                                 }
1318                                         } catch (Exception e) {
1319                                                 reqMessage = e.getMessage();
1320                                                 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1321                                                 throw new Exception(reqMessage);
1322                                         }
1323                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1324                                                         applicationsRestClientService, app.getId(), orgUserId);
1325                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1326                                                         userRolesInLocalApp);
1327                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1328                                         // Apply changes in external Access system
1329                                         updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
1330                                         logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1331                                                         newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1332                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1333                                 } 
1334                                 // If local application is not centralized 
1335                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1336                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1337                                                         applicationsRestClientService, app.getId(), orgUserId); 
1338                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1339                                                         userRolesInLocalApp);
1340                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1341                                 } else {// remote app
1342                                         // If adding just account admin role don't do remote application user call
1343                                         if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
1344                                         EPUser remoteAppUser = null;
1345                                                 remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, applicationsRestClientService);
1346                                         if (remoteAppUser == null) {
1347                                                 remoteAppUser = addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService);
1348                                                 reqMessage = "Saved Successfully";
1349                                         }
1350                                                 if (remoteAppUser != null) {
1351                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1352                                                                         mapper, applicationsRestClientService, app.getId(), orgUserId);
1353
1354                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1355                                                                         app.getId(), userRolesInRemoteApp);
1356                                                         logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1357                                                                         logMessage, newAppRolesForUser.getApplicationName(),
1358                                                                         newAppRolesForUser.getLoginId());
1359                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1360                                                                         reqType);
1361                                                         // If no roles remain, request app to set user inactive.
1362                                                         /*if (userRolesInRemoteApp.size() == 0) {
1363                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1364                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1365                                                                                 orgUserId);
1366                                                                 //TODO Need  to fix the logged in user is not set to inactive
1367                                                                 remoteAppUser.setActive(false);
1368                                                                 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
1369                                                         }*/
1370                                                 }
1371                                         } else {
1372                                                 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote 
1373                                                 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1374                                                         reqMessage = "Saved Successfully";
1375                                                 }
1376                                                 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1377
1378                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1379                                                                 userRolesInRemoteApp);
1380                                                 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1381                                                                 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1382                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1383                                                                 reqType);
1384                                         }
1385                                         if(!result){
1386                                                 reqMessage = "Failed to save the user app role(s)";
1387                                         }
1388                                         if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1389                                                 updateStatus = "C";
1390                                                 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1391                                         }
1392                                 }
1393                         } catch (Exception e) {
1394                                 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1395                                                 orgUserId, appName);
1396                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1397                                 result = false;
1398                                 reqMessage = e.getMessage();
1399                                  if(epRequestIdSize > 0 && !userInfo.isEmpty()){
1400                                  updateStatus = "F";
1401                                  applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1402                                  updateStatus, epRequestId.get(0));
1403                                  }
1404                         }
1405
1406                 }
1407                 return new ExternalRequestFieldsValidator(result, reqMessage);
1408         }
1409         
1410         /**
1411          * 
1412          * @param roleInAppForUserList
1413          * @param mapper
1414          * @param applicationsRestClientService
1415          * @param appId
1416          * @param userId
1417          * @return  Set<EcompRole>
1418          * @throws JsonProcessingException
1419          * @throws HTTPException
1420          */
1421         private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1422                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1423                         throws JsonProcessingException, HTTPException {
1424                 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1425                 return updatedUserRoles;
1426         }
1427         
1428         /**
1429          * It constructs and returns list of user app roles when the external API role approval system calls
1430          * this method
1431          * 
1432          * @param roleInAppForUserList
1433          * @param appId
1434          * @return list of user app roles
1435          * @throws Exception
1436          *                 throws exceptions if role id does not exits 
1437          */
1438         private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1439                         Long appId, String appName) throws Exception {
1440                 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1441                 EPRole existingAppRole = null;
1442                 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1443                         RoleInAppForUser ecompRole = new RoleInAppForUser();
1444                         existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1445                         if (existingAppRole == null) {
1446                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1447                                                 roleInAppForUserList);
1448                                 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1449                         }
1450                         if (!existingAppRole.getActive()) {
1451                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1452                                                 roleInAppForUserList);
1453                                 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1454                         } else {
1455                                 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1456                                 ecompRole.roleName = roleInAppForUser.getRoleName();
1457                                 ecompRole.isApplied = true;
1458                                 existingUserRoles.add(ecompRole);
1459                         }
1460                 }
1461                 return existingUserRoles;
1462         }
1463         
1464         
1465
1466         /**
1467          * 
1468          * @param userId
1469          * @param app
1470          * @param applicationsRestClientService
1471          * @return EPUser
1472          * @throws HTTPException
1473          */
1474         protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1475                         throws HTTPException {
1476                 // local app
1477                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1478                         // Map<String,String> params = new HashMap<String,String>();
1479                         // params.put("sbcid",userId);
1480                         @SuppressWarnings("unchecked")
1481                         List<EPUser> userList = (List<EPUser>) dataAccessService
1482                                         .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1483                         if (userList != null && !userList.isEmpty())
1484                                 return userList.get(0);
1485                         else
1486                                 return null;
1487                 }
1488                 // remote app
1489                 
1490                 return getUser(userId, app, applicationsRestClientService);
1491         }
1492         
1493         protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1494                         throws HTTPException {
1495                 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId));
1496
1497         }
1498         
1499         protected boolean isAppUpgradeVersion(EPApp app){
1500                 return true;
1501         }
1502         
1503         
1504         public ExternalSystemAccess getExternalRequestAccess(){
1505                 ExternalSystemAccess res = null; 
1506                 try {
1507                         res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1508                                         Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1509                 } catch (Exception e) {
1510                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1511                 }
1512                 return res;             
1513         }
1514         
1515         /*
1516          * (non-Javadoc)
1517          * 
1518          * @see org.openecomp.portalapp.portal.service.UserRolesService#
1519          * getAppRolesForUser(java.lang.Long, java.lang.String)
1520          */
1521         @SuppressWarnings("unchecked")
1522         public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1523
1524                 List<RoleInAppForUser> rolesInAppForUser = null;
1525                 EPApp app = appsService.getApp(appId);
1526                 try {
1527                         // for ecomp portal app, no need to make a remote call
1528                         if (appId == PortalConstants.PORTAL_APP_ID) {           
1529
1530                                 List<Role> roleList = roleService.getAvailableRoles(userId);
1531                                 List<Role> activeRoleList = new ArrayList<Role>();
1532                                 for(Role role: roleList) {
1533                                         if(role.getActive()) {
1534                                                 if(role.getId() != 1){ // prevent portal admin from being added
1535                                                         activeRoleList.add(role);
1536                                                 } else if(extRequestValue){
1537                                                         activeRoleList.add(role);
1538                                                 }
1539                                         }
1540                                                 
1541                                 }
1542                                 EPUser localUser  = getUserFromApp(userId, app, applicationsRestClientService);
1543                                 // If localUser does not exists return roles
1544                                 Set<EPRole> roleSet = null;
1545                                 EPRole[] roleSetList = null;
1546                                 if(localUser != null){
1547                                         roleSet = localUser.getAppEPRoles(app);
1548                                         roleSetList = roleSet.toArray(new EPRole[0]);
1549                                 }
1550                                 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1551                                 return rolesInAppForUser;
1552                         }
1553                         
1554                         EcompRole[] appRoles = null;
1555                         List<EcompRole> roles = new ArrayList<>();
1556                         if(app.getCentralAuth()){
1557                                 //Sync application roles from External Access System
1558                                 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
1559                                 List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);;
1560                                 for(EPRole role : applicationRoles){
1561                                         EcompRole ecompRole = new EcompRole();
1562                                         ecompRole.setId(role.getId());
1563                                         ecompRole.setName(role.getName());
1564                                         roles.add(ecompRole);
1565                                 }
1566                                 appRoles = roles.toArray(new EcompRole[roles.size()]);
1567                         } else{
1568                                 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1569                         }
1570                         // Test this error case, for generating an internal Ecomp Portal
1571                         // error
1572                         // EcompRole[] appRoles = null;
1573                         // If there is an exception in the rest client api, then null will
1574                         // be returned.
1575                         if (appRoles != null) {
1576                                 if(!app.getCentralAuth()) {
1577                                 syncAppRoles(sessionFactory, appId, appRoles);
1578                                 }
1579                                 EcompRole[] userAppRoles = null;
1580                                 try {
1581                                         try {
1582                                                 if(app.getCentralAuth()){
1583                                                         final Map<String, String> params = new HashMap<>();
1584                                                         final Map<String, Long> userParams = new HashMap<>();
1585                                                         params.put("orgUserIdValue", userId);
1586                                                         List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1587                                                         userParams.put("appId", app.getId());
1588                                                         userParams.put("userId", user.get(0).getId());  
1589                                                         List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1590                                                                 List<EcompRole> setUserRoles = new ArrayList<>();
1591                                                                 for(EPUserAppCurrentRoles role : userAppsRolesList){
1592                                                                         EcompRole ecompRole = new EcompRole();
1593                                                                         ecompRole.setId(role.getRoleId());
1594                                                                         ecompRole.setName(role.getRoleName());
1595                                                                         setUserRoles.add(ecompRole);
1596                                                                 }
1597                                                                 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1598                                                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1599                                                                 return rolesInAppForUser;
1600                                                 }else{
1601                                                         userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1602                                                                         String.format("/user/%s/roles", userId));
1603                                                 }
1604                                         } catch (HTTPException e) {
1605                                                 // Some apps are returning 400 if user is not found.
1606                                                 if (e.getResponseCode() == 400) {
1607                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1608                                                                         "getAppRolesForUser caught exception with response code 400; continuing", e);
1609                                                 } else {
1610                                                         // Other response code, let it come thru.
1611                                                         throw e;
1612                                                 }
1613                                         }
1614                                         if (userAppRoles == null) {
1615                                                 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1616                                                         EcompPortalUtils.setExternalAppResponseCode(200);
1617                                                         String message = String.format(
1618                                                                         "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1619                                                                                         + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1620                                                                                         + "Overriding to 200 until framework SDK returns a useful response.",
1621                                                                         Long.toString(appId), userId);
1622                                                         logger.warn(EELFLoggerDelegate.applicationLogger, message);
1623                                                 }
1624                                         }
1625                                         
1626                                          HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1627                                                 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1628                                                 for (int i = 0; i < userAppRoles.length; i++) {
1629                                                         if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1630                                                                 EcompRole role = new EcompRole();
1631                                                                 role.setId(userAppRoles[i].getId());
1632                                                                 role.setName(userAppRoles[i].getName());
1633                                                                 activeRoles.add(role);
1634                                                         }
1635                                                 }
1636                                                 EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1637                                         
1638                                         // If the remote application isn't down we MUST sync user
1639                                         // roles here in case we have this user here!
1640                                         syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1641                                 } catch (Exception e) {
1642                                         // TODO: we may need to check if user exists, maybe remote
1643                                         // app is down.
1644                                         String message = String.format(
1645                                                         "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1646                                                         Long.toString(appId));
1647                                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
1648                                         userAppRoles = new EcompRole[0];
1649                                 }
1650                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1651                         }
1652                 } catch (Exception e) {
1653                         String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1654                                         Long.toString(appId));
1655                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
1656                 }
1657                 return rolesInAppForUser;
1658
1659         }
1660         
1661         private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1662                         ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1663                         throws JsonProcessingException, HTTPException {
1664                 boolean result = false;
1665                 ObjectMapper mapper = new ObjectMapper();
1666                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1667                 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1668                 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1669                 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1670                 return result;
1671         }
1672
1673         public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1674                 FieldsValidator fieldsValidator = new FieldsValidator();
1675                 final Map<String, Long> params = new HashMap<>();
1676                 EPUserAppRoles  appRole= new EPUserAppRoles();
1677                 try {
1678                         logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1679                         boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1680                         
1681                         params.put("appId", userAppRolesData.appId);
1682                         EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1683                         epAppRolesRequestData.setCreatedDate(new Date());
1684                         epAppRolesRequestData.setUpdatedDate(new Date());
1685                         epAppRolesRequestData.setUserId(user.getId());
1686                         epAppRolesRequestData.setAppId(userAppRolesData.appId);
1687                         epAppRolesRequestData.setRequestStatus("P");
1688                         List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1689                         Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1690                         dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1691                         for (RoleInAppForUser userAppRoles : appRoleIdList) {
1692                                 Boolean isAppliedVal = userAppRoles.isApplied;
1693                                 params.put("appRoleId", userAppRoles.roleId);                           
1694                                 if (isAppliedVal) {
1695                                         appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
1696                                         EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1697                                         epAppRoleDetail.setReqRoleId(appRole.getRoleId());
1698                                         epAppRoleDetail.setReqType("P");
1699                                         epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1700                                         dataAccessService.saveDomainObject(epAppRoleDetail, null);
1701                                         }                       
1702                         }
1703                         epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1704                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1705
1706                 } catch (Exception e) {
1707                         logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1708                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1709                 }
1710                 return fieldsValidator;
1711         }
1712
1713         public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {      
1714                 Map<String, String> params = new HashMap<>();
1715                 params.put("userid", userid.getId().toString());
1716                 //params.put("appid", appid);
1717                 params.put("appName", appName);
1718                         
1719                 @SuppressWarnings("unchecked")
1720                 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1721                                 .executeNamedQuery("userAppCatalogRoles", params, null);
1722                 return userAppRoles;    
1723         }
1724         
1725         public String updateRemoteUserProfile(String orgUserId, Long appId) {
1726                 ObjectMapper mapper = new ObjectMapper();
1727                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1728                 EPUser client = searchService.searchUserByUserId(orgUserId);
1729                 EPUser newUser = new EPUser();
1730                 newUser.setActive(client.getActive());
1731                 newUser.setFirstName(client.getFirstName());
1732                 newUser.setLastName(client.getLastName());
1733                 newUser.setLoginId(client.getLoginId());
1734                 newUser.setLoginPwd(client.getLoginPwd());
1735                 newUser.setMiddleInitial(client.getMiddleInitial());
1736                 newUser.setEmail(client.getEmail());
1737                 newUser.setOrgUserId(client.getLoginId());
1738                 try {
1739                         String userAsString = mapper.writeValueAsString(newUser);
1740                         List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1741                         // applicationsRestClientService.post(EPUser.class, appId,
1742                         // userAsString, String.format("/user", orgUserId));
1743                         for (EPApp eachApp : appList) {
1744                                 try {
1745                                         applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1746                                                         String.format("/user/%s", orgUserId));
1747                                 } catch (Exception e) {
1748                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1749                                                         + " in remote app. appId = " + eachApp.getId());
1750                                 }
1751                         }
1752                 } catch (Exception e) {
1753                         logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1754                         return "failure";
1755                 }
1756
1757                 return "success";
1758         }
1759
1760
1761         /*
1762          * (non-Javadoc)
1763          * 
1764          * @see org.openecomp.portalapp.portal.service.UserRolesService#
1765          * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1766          */
1767         public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1768                 // Find the records for this user-app combo, if any
1769                 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1770                 @SuppressWarnings("unchecked")
1771                 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1772                 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
1773                 return roleList;
1774         }
1775
1776 }