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