Application Onboarding page changes
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / UserRolesCommonServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38
39 package org.onap.portalapp.portal.service;
40
41 import java.io.IOException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.Date;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.LinkedHashSet;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Set;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
54 import java.util.stream.Collectors;
55
56 import javax.servlet.http.HttpServletResponse;
57
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.cxf.transport.http.HTTPException;
60 import org.hibernate.SQLQuery;
61 import org.hibernate.Session;
62 import org.hibernate.SessionFactory;
63 import org.hibernate.Transaction;
64 import org.json.JSONArray;
65 import org.json.JSONObject;
66 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
67 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
68 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
69 import org.onap.portalapp.portal.domain.EPApp;
70 import org.onap.portalapp.portal.domain.EPRole;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserApp;
73 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRoles;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
76 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
77 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
78 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
83 import org.onap.portalapp.portal.transport.CentralV2Role;
84 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
85 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
86 import org.onap.portalapp.portal.transport.ExternalAccessUser;
87 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
89 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
90 import org.onap.portalapp.portal.transport.FieldsValidator;
91 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
92 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
93 import org.onap.portalapp.portal.transport.RemoteRole;
94 import org.onap.portalapp.portal.transport.RemoteRoleV1;
95 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
96 import org.onap.portalapp.portal.transport.RoleInAppForUser;
97 import org.onap.portalapp.portal.transport.RolesInAppForUser;
98 import org.onap.portalapp.portal.transport.UserApplicationRoles;
99 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
100 import org.onap.portalapp.portal.utils.EcompPortalUtils;
101 import org.onap.portalapp.portal.utils.PortalConstants;
102 import org.onap.portalapp.util.EPUserUtils;
103 import org.onap.portalapp.util.SystemType;
104 import org.onap.portalsdk.core.domain.Role;
105 import org.onap.portalsdk.core.domain.RoleFunction;
106 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
107 import org.onap.portalsdk.core.restful.domain.EcompRole;
108 import org.onap.portalsdk.core.service.DataAccessService;
109 import org.onap.portalsdk.core.service.RoleService;
110 import org.onap.portalsdk.core.util.SystemProperties;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.springframework.http.HttpEntity;
113 import org.springframework.http.HttpHeaders;
114 import org.springframework.http.HttpMethod;
115 import org.springframework.http.HttpStatus;
116 import org.springframework.http.ResponseEntity;
117 import org.springframework.web.client.HttpClientErrorException;
118 import org.springframework.web.client.RestTemplate;
119
120 import com.fasterxml.jackson.core.JsonProcessingException;
121 import com.fasterxml.jackson.databind.DeserializationFeature;
122 import com.fasterxml.jackson.databind.ObjectMapper;
123
124 @EPMetricsLog
125 public class UserRolesCommonServiceImpl  {
126
127         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
128
129         private static final Object syncRests = new Object();
130
131         private static final String APP_ID = "appId";
132                 
133         @Autowired
134         private DataAccessService dataAccessService;                            
135         @Autowired
136         private SessionFactory sessionFactory;
137         @Autowired
138         private SearchService searchService;
139         @Autowired
140         private EPAppService appsService;
141         @Autowired
142         private ApplicationsRestClientService applicationsRestClientService;
143         @Autowired
144         private EPRoleService epRoleService;
145         @Autowired
146         private RoleService roleService;        
147         @Autowired
148         private AdminRolesService adminRolesService;
149         @Autowired
150         private EPAppService appService;
151         @Autowired
152         private ExternalAccessRolesService externalAccessRolesService;
153         
154         @Autowired
155         private AppsCacheService appsCacheService;
156         
157         RestTemplate template = new RestTemplate();
158         
159         /**
160          * 
161          * @param ecompRoles
162          * @return  HashMap<Long, EcompRole>
163          */
164         private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
165                 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
166                 if (ecompRoles != null) {
167                         for (int i = 0; i < ecompRoles.length; i++) {
168                                 if (ecompRoles[i].getId() != null) {
169                                         result.put(ecompRoles[i].getId(), ecompRoles[i]);
170                                 }
171                         }
172                 }
173                 return result;
174         }
175         
176         /**
177          * 
178          * @param userId
179          */
180         protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) {
181                 if (StringUtils.isEmpty(userId)) {
182                         logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
183                         return;
184                 }
185                 Session localSession = null;
186                 Transaction transaction = null;
187                 try {
188                         localSession = sessionFactory.openSession();
189                         transaction = localSession.beginTransaction();
190                         @SuppressWarnings("unchecked")
191                         List<EPUser> userList = localSession
192                                         .createQuery("from :name where orgUserId=:userId")
193                                         .setParameter("name",EPUser.class.getName())
194                                         .setParameter("userId",userId)
195                                         .list();
196                         if (userList.size() == 0) {
197                                 EPUser client = null;
198                                 if (!isSystemUser) {
199                                         client = searchService.searchUserByUserId(userId);
200                                 } else {
201                                         client = new EPUser();
202                                         client.setOrgUserId(userId);
203                                         client.setSystemUser(true);
204                                         client.setFirstName(userId.substring(0,userId.indexOf("@")));
205                                 }
206                                 if (client == null) {
207                                         String msg = "createLocalUserIfNecessary: cannot create user " + userId
208                                                         + ", because not found in phonebook";
209                                         logger.error(EELFLoggerDelegate.errorLogger, msg);
210                                 } else {
211                                         client.setLoginId(userId);
212                                         client.setActive(true);
213                                         localSession.save(client);
214                                 }
215                         }
216                         transaction.commit();
217                 } catch (Exception e) {
218                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
219                         EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
220                 } finally {
221                         EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
222                 }
223         }
224         
225         /**
226          * This method return nothing and remove roles before adding any roles for an app
227          * @param userRole
228          * @param appId
229          * @param localSession
230          * @param userAppRoles
231          * @param newUserAppRolesMap
232          */
233         private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
234
235                 Long userAppRoleId = 0L;
236                 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
237                         userAppRoleId = userRole.getRoleId();
238                 } else { // remote app
239                         userAppRoleId = userRole.getAppRoleId();
240                 }
241
242                 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
243                         localSession.delete(userRole);
244                 } else {
245                         newUserAppRolesMap.remove(userAppRoleId);
246                 }
247         }
248         
249         /**
250          * Checks whether the role is inactive
251          *  
252          * @param epRole
253          * @throws Exception
254          *                      if role is inactive, throws exception
255          */
256         private void checkIfRoleInactive(EPRole epRole) throws Exception{       
257                 if(!epRole.getActive()){
258                         throw new Exception(epRole.getName()+ " role is unavailable");
259                 }
260         }
261         
262         /**
263          * 
264          * @param sessionFactory
265          * @param userId
266          * @param appId
267          * @param userAppRoles
268          * @param extRequestValue 
269          *                      set to false if request is from users page otherwise true
270          * @throws Exception
271          */
272         protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
273                         EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
274                 Session localSession = null;
275                 Transaction transaction = null;
276                 String roleActive = null;
277                 final Map<String, String> userAppParams = new HashMap<>();
278                 final Map<String, String> appParams = new HashMap<>();
279                 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
280
281                 try {
282                         localSession = sessionFactory.openSession();
283                         transaction = localSession.beginTransaction();
284                         @SuppressWarnings("unchecked")
285                         List<EPUser> userList = localSession
286                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
287                         if (userList.size() > 0) {
288                                 EPUser client = userList.get(0);
289                                 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
290                                 @SuppressWarnings("unchecked")
291                                 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
292                                                 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
293                                 
294                                 if ("DELETE".equals(reqType)) {
295                                         for (EPUserApp userAppRoleList : userRoles) {
296                                                 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
297                                                 userAppParams.put("appId",  String.valueOf(appId));
298                                                 appParams.put("appRoleName", userAppRoleList.getRole().getName());
299                                                 @SuppressWarnings("unchecked")
300                                                 List<EPRole>  rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);        
301                                                 if(rolesList.size() > 0 || !rolesList.isEmpty()){
302                                                 checkIfRoleInactive(rolesList.get(0));
303                                                 }
304                                         }
305                                 }
306
307                                 for (EPUserApp userRole : userRoles) {
308                                         if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
309                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
310                                                 }
311                                         else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
312                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
313                                         }
314                                         else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
315                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
316                                         }
317                                 }
318                                 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
319                                 if (newRolesToAdd.size() > 0) {
320                                         EPApp app = (EPApp) localSession.get(EPApp.class, appId);
321
322                                         HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
323                                         if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
324                                                 String appIdValue = "";
325                                                 if(!extRequestValue){
326                                                         appIdValue = "and id != " +  PortalConstants.SYS_ADMIN_ROLE_ID; 
327                                                 }
328                                                 @SuppressWarnings("unchecked")
329                                                 List<EPRole> roles = localSession
330                                                                 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
331                                                 for (EPRole role : roles) {
332                                                         role.setAppId(1L);
333                                                         rolesMap.put(role.getId(), role);
334                                                 }
335                                         } else { // remote app
336                                                 @SuppressWarnings("unchecked")
337                                                 List<EPRole> roles = localSession
338                                                                 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
339                                                 for (EPRole role : roles) {
340                                                         if (!extRequestValue && app.getCentralAuth()) {
341                                                                 rolesMap.put(role.getId(), role);
342                                                         } else {
343                                                                 rolesMap.put(role.getAppRoleId(), role);
344                                                         }
345                                                 }
346                                         }
347
348                                         EPRole role = null;
349                                         for (EcompRole userRole : newRolesToAdd) {
350                                                 EPUserApp userApp = new EPUserApp();
351                                                 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
352                                                         role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
353                                                         userApp.setRole(role);
354                                                 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
355                                                                 continue;
356                                                 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
357                                                         continue;
358                                                 }                                               
359                                                 else {
360                                                         userApp.setRole(rolesMap.get(userRole.getId()));
361                                                 }
362
363                                                 userApp.setUserId(client.getId());
364                                                 userApp.setApp(app);
365                                                 localSession.save(userApp);
366                                                 localSession.flush();
367                                         }
368
369                                         if (appId == PortalConstants.PORTAL_APP_ID) {
370                                                 /*
371                                                  * for local app -- hack - always make sure fn_role
372                                                  * table's app_id is null and not 1 for primary app in
373                                                  * this case being onap portal app; reason: hibernate
374                                                  * is rightly setting this to 1 while persisting to
375                                                  * fn_role as per the mapping but SDK role management
376                                                  * code expects the app_id to be null as there is no
377                                                  * concept of App_id in SDK
378                                                  */
379                                                 localSession.flush();
380                                                 SQLQuery sqlQuery = localSession
381                                                                 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
382                                                 sqlQuery.executeUpdate();
383                                                 
384                                         }
385                                 }
386                         }
387                         transaction.commit();
388                 } catch (Exception e) {
389                         logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
390                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
391                         EcompPortalUtils.rollbackTransaction(transaction,
392                                         "Exception occurred in syncUserRoles, Details: " + e.toString());
393                         if("DELETE".equals(reqType)){
394                                 throw new SyncUserRolesException(e.getMessage());
395                         }
396                 } finally {
397                         if(localSession != null)
398                                 localSession.close();
399                 }
400         }
401         
402         /**
403          * Called when getting the list of roles for the user
404          * 
405          * @param appRoles
406          * @param userAppRoles
407          * @return List<RoleInAppForUser> 
408          */
409         protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
410                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
411
412                 Set<Long> userAppRolesMap = new HashSet<Long>();
413                 if (userAppRoles != null) {
414                         for (EcompRole ecompRole : userAppRoles) {
415                                 userAppRolesMap.add(ecompRole.getId());
416                         }
417                 } else {
418                         logger.error(EELFLoggerDelegate.errorLogger,
419                                         "constructRolesInAppForUserGet has received userAppRoles list empty");
420                 }
421
422                 if (appRoles != null) {
423                         for (EcompRole ecompRole : appRoles) {
424                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
425                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
426                                 rolesInAppForUser.add(roleForUser);
427                         }
428                 } else {
429                         logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
430                 }
431                 return rolesInAppForUser;
432         }
433
434         /**
435          * Called when getting the list of roles for the user
436          * 
437          * @param appRoles
438          * @param userAppRoles
439          * @param extRequestValue 
440          *                      set to false if request is from users page otherwise true
441          * @return List<RoleInAppForUser>
442          */
443         protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
444                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
445
446                 Set<Long> userAppRolesMap = new HashSet<Long>();
447                 if (userAppRoles != null) {
448                         for (EPRole ecompRole : userAppRoles) {
449                                 userAppRolesMap.add(ecompRole.getId());
450                         }
451                         logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
452
453                 } else {
454                         logger.error(EELFLoggerDelegate.errorLogger,
455                                         "constructRolesInAppForUserGet has received userAppRoles list empty.");
456                 }
457
458                 if (appRoles != null) {
459
460                         for (Role ecompRole : appRoles) {
461                                 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
462
463                                 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
464                                         continue;
465                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
466                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
467                                 rolesInAppForUser.add(roleForUser);
468                                 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
469
470                         }
471                 } else {
472                         logger.error(EELFLoggerDelegate.errorLogger,
473                                         "constructRolesInAppForUser has received appRoles list empty.");
474                 }
475                 return rolesInAppForUser;
476         }
477
478         
479         /**
480          * copies of methods in GetAppsWithUserRoleState
481          * 
482          * @param sessionFactory
483          * @param appId
484          * @param appRoles
485          * @throws Exception
486          */
487         protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
488                 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
489                 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
490                 Session localSession = null;
491                 Transaction transaction = null;
492
493                 try {
494                         localSession = sessionFactory.openSession();
495                         transaction = localSession.beginTransaction();
496                         // Attention! All roles from remote application supposed to be
497                         // active!
498                         @SuppressWarnings("unchecked")
499                         List<EPRole> currentAppRoles = localSession
500                                         .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
501                         List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
502                         for (int i = 0; i < currentAppRoles.size(); i++) {
503                                 EPRole oldAppRole = currentAppRoles.get(i);
504                                 if (oldAppRole.getAppRoleId() != null) {
505                                         EcompRole role = null;
506                                         role = newRolesMap.get(oldAppRole.getAppRoleId());
507                                         if (role != null) {
508                                                 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
509                                                         oldAppRole.setName(role.getName());
510                                                         localSession.update(oldAppRole);
511                                                 }
512                                                 oldAppRole.setActive(true);
513                                                 newRolesMap.remove(oldAppRole.getAppRoleId());
514                                         } else {
515                                                 obsoleteRoles.add(oldAppRole);
516                                         }
517                                 } else {
518                                         obsoleteRoles.add(oldAppRole);
519                                 }
520                         }
521                         Collection<EcompRole> newRolesToAdd = newRolesMap.values();
522                         if (obsoleteRoles.size() > 0) {
523                                 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
524                                 for (EPRole role : obsoleteRoles) {
525                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
526                                         Long roleId = role.getId();
527                                         // delete obsolete roles here
528                                         // Must delete all records with foreign key constraints on
529                                         // fn_role:
530                                         // fn_user_role, fn_role_composite, fn_role_function,
531                                         // fn_user_pseudo_role, fn_menu_functional_roles.
532                                         // And for fn_menu_functional, if no other roles for that
533                                         // menu item, remove the url.
534
535                                         // Delete from fn_user_role
536                                         @SuppressWarnings("unchecked")
537                                         List<EPUserApp> userRoles = localSession.createQuery(
538                                                         "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
539                                                         .list();
540
541                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
542                                         for (EPUserApp userRole : userRoles) {
543                                                 logger.debug(EELFLoggerDelegate.debugLogger,
544                                                                 "syncAppRoles: about to delete userRole: " + userRole.toString());
545                                                 localSession.delete(userRole);
546                                                 logger.debug(EELFLoggerDelegate.debugLogger,
547                                                                 "syncAppRoles: finished deleting userRole: " + userRole.toString());
548                                         }
549
550                                         // Delete from fn_menu_functional_roles
551                                         @SuppressWarnings("unchecked")
552                                         List<FunctionalMenuRole> funcMenuRoles = localSession
553                                                         .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
554                                                         .list();
555                                         int numMenuRoles = funcMenuRoles.size();
556                                         logger.debug(EELFLoggerDelegate.debugLogger,
557                                                         "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
558                                         for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
559                                                 Long menuId = funcMenuRole.menuId;
560                                                 // If this is the only role for this menu item, then the
561                                                 // app and roles will be gone,
562                                                 // so must null out the url too, to be consistent
563                                                 @SuppressWarnings("unchecked")
564                                                 List<FunctionalMenuRole> funcMenuRoles2 = localSession
565                                                                 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
566                                                                 .list();
567                                                 int numMenuRoles2 = funcMenuRoles2.size();
568                                                 logger.debug(EELFLoggerDelegate.debugLogger,
569                                                                 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
570                                                 localSession.delete(funcMenuRole);
571                                                 if (numMenuRoles2 == 1) {
572                                                         // If this is the only role for this menu item, then
573                                                         // the app and roles will be gone,
574                                                         // so must null out the url too, to be consistent
575                                                         logger.debug(EELFLoggerDelegate.debugLogger,
576                                                                         "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
577                                                         @SuppressWarnings("unchecked")
578                                                         List<FunctionalMenuItem> funcMenuItems = localSession
579                                                                         .createQuery(
580                                                                                         "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
581                                                                         .list();
582                                                         if (funcMenuItems.size() > 0) {
583                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
584                                                                 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
585                                                                 funcMenuItem.url = "";
586                                                                 localSession.update(funcMenuItem);
587                                                         }
588                                                 }
589                                         }
590                                         boolean isPortalRequest = true;
591                                         externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
592                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
593                                         localSession.delete(role);
594                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
595                                 }
596                         }
597                         for (EcompRole role : newRolesToAdd) {
598                                 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
599                                 EPRole newRole = new EPRole();
600                                 // Attention! All roles from remote application supposed to be
601                                 // active!
602                                 newRole.setActive(true);
603                                 newRole.setName(role.getName());
604                                 newRole.setAppId(appId);
605                                 newRole.setAppRoleId(role.getId());
606                                 localSession.save(newRole);
607                         }
608                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
609                         transaction.commit();
610                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
611                 } catch (Exception e) {
612                         logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
613                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
614                         EcompPortalUtils.rollbackTransaction(transaction,
615                                         "Exception occurred in syncAppRoles, Details: " + e.toString());
616                         throw new Exception(e);
617                 } finally {
618                         localSession.close();
619                 }
620         }
621         
622         
623         
624         
625         
626         /**
627          * Called when updating the list of roles for the user
628          * 
629          * @param userId
630          * @param appId
631          * @param userRolesInRemoteApp
632          * @return RolesInAppForUser
633          */
634         protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
635                         Set<EcompRole> userRolesInRemoteApp) {
636                 RolesInAppForUser result;
637                 result = new RolesInAppForUser();
638                 result.appId = appId;
639                 result.orgUserId = userId;
640
641                 for (EcompRole role : userRolesInRemoteApp) {
642                         RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
643                         roleInAppForUser.roleId = role.getId();
644                         roleInAppForUser.roleName = role.getName();
645                         roleInAppForUser.isApplied = new Boolean(true);
646                         result.roles.add(roleInAppForUser);
647                 }
648                 return result;
649         }
650         
651         /**
652          * 
653          * @param roleInAppForUserList
654          * @return boolean
655          */
656         protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
657                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
658                         if (roleInAppForUser.isApplied.booleanValue()) {
659                                 return true;
660                         }
661                 }
662                 return false;
663         }
664         
665         /**
666          * Builds JSON and posts it to a remote application to update user roles.
667          * 
668          * @param roleInAppForUserList
669          * @param mapper
670          * @param applicationsRestClientService
671          * @param appId
672          * @param userId
673          * @return Set of roles as sent; NOT the response from the app.
674          * @throws JsonProcessingException
675          * @throws HTTPException
676          */
677         protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
678                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
679                         throws JsonProcessingException, HTTPException {
680                 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
681                 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
682                 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
683         EPApp externalApp = null;
684         SystemType type = SystemType.APPLICATION;
685                 externalApp = appsCacheService.getApp(appId);
686                 String appBaseUri = null;
687                 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
688                 if (externalApp != null) {
689                          appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
690                 }
691                 if(appBaseUri != null && appBaseUri.endsWith("/api")){
692                         for(EcompRole eprole :updatedUserRolesinRemote)
693                         {
694                                 RemoteRoleV1 role = new RemoteRoleV1();
695                                 role.setId(eprole.getId());
696                                 role.setName(eprole.getName());
697                                 updatedUserRolesinRemoteV1.add(role);
698                         }
699                         userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
700                 }
701                 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
702                                 String.format("/user/%s/roles", userId));
703                 // TODO: We should add code that verifies that the post operation did
704                 // succeed. Because the SDK may still return 200 OK with an html page
705                 // even when it fails!
706                 return updateUserRolesInEcomp;
707         }
708         
709         /**
710          * 
711          * @param roleInAppForUserList
712          * @return Set<EcompRole> 
713          */
714         protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
715                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
716                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
717                         if (roleInAppForUser.isApplied) {
718                                 EcompRole ecompRole = new EcompRole();
719                                 ecompRole.setId(roleInAppForUser.roleId);
720                                 ecompRole.setName(roleInAppForUser.roleName);
721                                 existingUserRoles.add(ecompRole);
722                         }
723                 }
724                 return existingUserRoles;
725         }
726         
727         /**
728          * Constructs user app roles excluding Account Administrator role
729          * 
730          * @param roleInAppForUserList
731          * @return
732          *            List of roles with Role name, Role Id
733          */
734         protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
735                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
736                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
737                         if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
738                                 EcompRole ecompRole = new EcompRole();
739                                 ecompRole.setId(roleInAppForUser.roleId);
740                                 ecompRole.setName(roleInAppForUser.roleName);
741                                 existingUserRoles.add(ecompRole);
742                         }
743                 }
744                 return existingUserRoles;
745         }
746         
747         /**
748          * This is for a single app
749          * 
750          * @param rolesInAppForUser
751          * @param externalSystemRequest  
752          *                      set to false if requests from Users page otherwise true
753          * @return true on success, false otherwise
754          */
755         protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
756                 boolean result = false;
757                 String userId = rolesInAppForUser.orgUserId;
758                 Long appId = rolesInAppForUser.appId;
759                 synchronized (syncRests) {
760                         if (rolesInAppForUser != null) {
761                                 createLocalUserIfNecessary(userId, isSystemUser);
762                         }
763
764                         if (rolesInAppForUser != null) {
765                                 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
766                                 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
767                                         RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
768                                         EcompRole role = new EcompRole();
769                                         role.setId(roleInAppForUser.roleId);
770                                         role.setName(roleInAppForUser.roleName);
771                                         userAppRoles[i] = role;
772                                 }
773                                 try {
774                                         syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
775                                         result = true;
776                                 } catch (Exception e) {
777                                         logger.error(EELFLoggerDelegate.errorLogger,
778                                                         "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
779                                         if("DELETE".equals(reqType)){
780                                                 throw new Exception(e.getMessage());
781                                         }
782                                 }
783                         }
784                 }
785                 return result;
786         }
787         
788         /**
789          * 
790          * @param appId
791          * @param remoteUser
792          * @return UserApplicationRoles
793          */
794         protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
795                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
796                 userWithRemoteAppRoles.setAppId(appId);
797                 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
798                 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
799                 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
800                 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
801                 return userWithRemoteAppRoles;
802         }
803         
804         /*
805          * (non-Javadoc)
806          * 
807          * @see org.onap.portalapp.portal.service.UserRolesService#
808          * importRolesFromRemoteApplication(java.lang.Long)
809          */
810         public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
811                 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
812                 List<EPRole> rolesList = Arrays.asList(appRolesFull);
813                 for (EPRole externalAppRole : rolesList) {
814
815                         // Try to find an existing extern role for the app in the local
816                         // onap DB. If so, then use its id to update the existing external
817                         // application role record.
818                         Long externAppId = externalAppRole.getId();
819                         EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
820                         if (existingAppRole != null) {
821                                 logger.debug(EELFLoggerDelegate.debugLogger,
822                                                 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
823                                                                 appId, externAppId));
824                                 continue;
825                         }
826                         // persistExternalRoleInEcompDb(externalAppRole, appId,
827                         // roleService);
828                 }
829
830                 return rolesList;
831         }
832         
833         /**
834          * It adds new user for remote application
835          * 
836          * @param roleInAppForUserList
837          * @param remoteAppUser
838          * @param userId
839          * @param app
840          * @param mapper
841          * @param searchService
842          * @param applicationsRestClientService
843          * @return 
844          * @throws Exception
845          */
846         private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
847                         ObjectMapper mapper, SearchService searchService,
848                         ApplicationsRestClientService applicationsRestClientService) throws Exception {
849                 EPUser addRemoteUser = null;
850                 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
851                         createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
852                                         isAppUpgradeVersion(app));
853                 }
854                 return addRemoteUser;
855         }
856         
857         private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
858                         ObjectMapper mapper, SearchService searchService,
859                         ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
860                 EPUser addRemoteUser = null;
861 //              if (remoteUserShouldBeCreated(roleInAppForUserList)) {
862                         pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
863                                         isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
864 //              }
865                 return addRemoteUser;
866         }
867
868         @SuppressWarnings("unchecked")
869         protected void pushUserOnRemoteApp(String userId, EPApp app,
870                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
871                         ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
872
873                 EPUser client  = null;
874                         client = searchService.searchUserByUserId(userId);
875
876                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
877                         if (client == null) {
878                                 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
879                                 logger.error(EELFLoggerDelegate.errorLogger, msg);
880                                 // throw new Exception(msg);
881                                 final Map<String, String> loginIdParams = new HashMap<>();
882                                 loginIdParams.put("orgUserIdValue", userId);
883                                 List<EPUser> userList = new ArrayList<>();
884                                 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
885                                 if (userList.size() > 0) {
886                                         logger.debug(EELFLoggerDelegate.debugLogger,
887                                                         userList.get(0).getOrgUserId() + " User was found in Portal");
888                                         client = userList.get(0);
889                                         SortedSet<EPUserApp> userApps = new TreeSet<>();
890                                         client.setEPUserApps(userApps);
891                                         client.setSystemUser(false);
892                                 } else {
893                                         logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
894                                         throw new Exception(msg);
895                                 }
896
897                         }
898                 
899                 client.setLoginId(userId);
900             client.setActive(true);
901             client.setOrgUserId(userId);
902         
903                 
904                 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
905                 SortedSet<Role> roles = new TreeSet<>();
906
907                 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
908                 List<EPApp> appList = new ArrayList<>();
909                 appList.add(app);
910                 List<CentralV2Role> roleList = new ArrayList<>();
911                 Map<String, Long> params = new HashMap<>();
912
913                 List<EPRole> userRoles = new ArrayList<>();
914
915                 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
916                         EPRole role = new EPRole();
917                         role.setId(roleInappForUser.getRoleId());
918                         role.setName(roleInappForUser.getRoleName());
919                         userRoles.add(role);
920                 }
921
922                 if (appRoleIdUsed) {
923                         List<EPRole> userAppRoles = new ArrayList<>();
924                         for (EPRole role : userRoles) {
925                                 EPRole appRole = getAppRoles.stream()
926                                                 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
927                                                 .orElse(null);
928                                 EPRole epRole = new EPRole();
929                                 if (appRole != null) {
930                                         epRole.setId(appRole.getId());
931                                         epRole.setName(appRole.getName());
932                                 }
933                                 userAppRoles.add(epRole);
934                         }
935                         userRoles = new ArrayList<>();
936                         userRoles.addAll(userAppRoles);
937                 }
938                 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
939
940                 for (CentralV2Role epRole : roleList) {
941                         Role role = new Role();
942                         EPRole appRole = getAppRoles.stream()
943                                         .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
944                         if (appRole != null){
945                                 role.setId(appRole.getAppRoleId());
946                         role.setName(epRole.getName());
947                         role.setRoleFunctions(epRole.getRoleFunctions());
948                         }
949                         roles.add(role);
950                 }
951                 client.setRoles(roles);
952                 String userInString = null;
953                 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
954                 logger.debug(EELFLoggerDelegate.debugLogger,
955                                 "about to post a client to remote application, users json = " + userInString);
956                 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
957         }
958
959         /**
960          * It checks whether the remote user exists or not
961          * if exits returns user object else null
962          * 
963          * @param userId
964          * @param app
965          * @param applicationsRestClientService
966          * @return
967          * @throws HTTPException
968          */
969         private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
970                 EPUser checkRemoteUser = null;
971                 try {
972                         checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
973                 } catch (HTTPException e) {
974                         // Some apps are returning 400 if user is not found.
975                         if (e.getResponseCode() == 400) {
976                                 logger.debug(EELFLoggerDelegate.debugLogger,
977                                                 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
978                                                 e);
979                         } else if(e.getResponseCode() == 404) {
980                                 logger.debug(EELFLoggerDelegate.debugLogger,
981                                                 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
982                                                 e);
983                         } else {
984                                 // Other response code, let it come thru.
985                                 throw e;
986                         }
987                 }
988                 return checkRemoteUser;
989         }
990         
991         
992         /*
993          * (non-Javadoc)
994          * 
995          * @see org.onap.portalapp.portal.service.UserRolesService#
996          * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
997          * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
998          */
999         public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1000                 boolean result = false;
1001                 boolean epRequestValue = false;
1002                 String userId = "";
1003                 String reqMessage = "";
1004                 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
1005                         userId = newAppRolesForUser.orgUserId.trim();
1006                 }
1007                 Long appId = newAppRolesForUser.appId;
1008                 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
1009                 if (userId.length() > 0 ) {
1010                         ObjectMapper mapper = new ObjectMapper();
1011                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1012
1013                         try {
1014                                 EPApp app = appsService.getApp(appId);
1015                                 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1016
1017                                 boolean systemUser = newAppRolesForUser.isSystemUser;
1018                                 if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1019
1020                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1021                                                         applicationsRestClientService, appId, userId);
1022                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1023                                                         userRolesInLocalApp);
1024                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1025                                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1026                                                 // Apply changes in external Access system
1027                                                 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1028                                                                 epRequestValue, systemUser);
1029                                         }
1030                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1031                                                         systemUser);
1032
1033                                 }else if (!app.getCentralAuth() && systemUser)
1034                                 {
1035                                         throw new Exception("For non-centralized application we cannot add systemUser");
1036                                 }
1037                                 else{   // if centralized app
1038                                 if (app.getCentralAuth()) {
1039                                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1040                                                 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1041                                                                         applicationsRestClientService,false);
1042                                         }
1043                                         
1044                                         Set<EcompRole>  userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1045                                                         applicationsRestClientService, appId, userId);
1046                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1047                                                         userRolesInLocalApp);
1048                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1049                                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1050                                                 // Apply changes in external Access system
1051                                                 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1052                                                                 epRequestValue,false);
1053                                         }
1054                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
1055                                 } 
1056                                 // In case if portal is not centralized then follow existing approach
1057                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1058                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1059                                                         applicationsRestClientService, appId, userId);  
1060                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1061                                                         userRolesInLocalApp);
1062                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
1063                                 } else{// remote app
1064                                         EPUser remoteAppUser = null;
1065                                         if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1066                                                 
1067                                                 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1068                 
1069                                                 if (remoteAppUser == null) {
1070                                                         remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1071                                                 }
1072                                                 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1073                                                                         applicationsRestClientService, appId, userId,systemUser);
1074                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1075                                                                         userRolesInRemoteApp);
1076                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
1077
1078                                                         // If no roles remain, request app to set user inactive.
1079                                                         if (userRolesInRemoteApp.size() == 0) {
1080                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1081                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1082                                                                                 userId);
1083                                                                 //remoteAppUser.setActive(false);
1084                                                                 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1085                                                 }
1086                                         }
1087                                 }
1088                         }
1089                         } catch (Exception e) {
1090                                 /*String message = String.format(
1091                                                 "Failed to create user or update user roles for User %s, AppId %s",
1092                                                 userId, Long.toString(appId));
1093                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1094                                 result = false;*/
1095
1096                                 String message = String.format(
1097                                                 "Failed to create user or update user roles for User %s, AppId %s",
1098                                                 userId, Long.toString(appId));
1099                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1100                                 result = false;
1101                                 reqMessage = e.getMessage();
1102                                                          
1103                         
1104                         }
1105
1106                 }
1107                 //return result;
1108                 return new ExternalRequestFieldsValidator(result, reqMessage);
1109
1110         }
1111         /**
1112          * It adds user roles in External system and also make data consistent in both local and in External System 
1113          * 
1114          * @param app details
1115          * @param orgUserId
1116          * @param roleInAppUser Contains list of active roles 
1117          */
1118         @SuppressWarnings("unchecked")
1119         private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
1120         {
1121                 try {
1122                         // check if user exists
1123                         final Map<String, String> userParams = new HashMap<>();
1124                         userParams.put("orgUserIdValue", orgUserId);
1125                         List<EPUser> userInfo = checkIfUserExists(userParams);
1126                         if (userInfo.isEmpty()) {
1127                                 createLocalUserIfNecessary(orgUserId, isSystemUser);
1128                         }
1129                         String name = "";
1130                         if (EPCommonSystemProperties
1131                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
1132                                 name = orgUserId
1133                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1134                         } else {
1135                                 name = orgUserId;
1136                         }
1137                         ObjectMapper mapper = new ObjectMapper();
1138                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1139                         HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1140                         ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1141                         List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1142                         String res = getResponse.getBody();
1143                         JSONObject jsonObj = null;
1144                         JSONArray extRoles = null;
1145                         if (!res.equals("{}")) {
1146                                 jsonObj = new JSONObject(res);
1147                                 extRoles = jsonObj.getJSONArray("role");
1148                         }
1149                         ExternalAccessUserRoleDetail userRoleDetail = null;
1150                         if (extRoles != null) {
1151                                 for (int i = 0; i < extRoles.length(); i++) {
1152                                         if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1153                                                         && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1154                                                         && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1155                                                 if (extRoles.getJSONObject(i).has("description")) {
1156                                                         ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1157                                                         userRoleDetail = new ExternalAccessUserRoleDetail(
1158                                                                         extRoles.getJSONObject(i).getString("name"), desc);
1159                                                         userRoleDetailList.add(userRoleDetail);
1160                                                 } else {
1161                                                         userRoleDetail = new ExternalAccessUserRoleDetail(
1162                                                                         extRoles.getJSONObject(i).getString("name"), null);
1163                                                         userRoleDetailList.add(userRoleDetail);
1164                                                 }
1165
1166                                         }
1167                                 }
1168                         }
1169                         
1170                         List<ExternalAccessUserRoleDetail>  userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1171                         
1172                         // If request coming from portal not from external role approval system then we have to check if user already 
1173                         // have account admin or system admin as GUI will not send these roles 
1174                         if (!isPortalRequest) {
1175                                 final Map<String, String> loginIdParams = new HashMap<>();
1176                                 loginIdParams.put("orgUserIdValue", orgUserId);
1177                                 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1178                                 final Map<String, Long> params = new HashMap<>();
1179                                 params.put("appId", app.getId());
1180                                 params.put("userId", user.getId());
1181                                 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1182                                                 params, null);
1183                                 if (!roleInAppUser.isEmpty()) {
1184                                         for (EcompUserAppRoles userApp : userAppList) {
1185                                                 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1186                                                                 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1187                                                         RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1188                                                         addSpecialRole.setIsApplied(true);
1189                                                         addSpecialRole.setRoleId(userApp.getRoleId());
1190                                                         addSpecialRole.setRoleName(userApp.getRoleName());
1191                                                         roleInAppUser.add(addSpecialRole);
1192                                                 }
1193                                         }
1194                                 }
1195                         }
1196                         List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1197                                         .collect(Collectors.toList());
1198                         final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1199                         for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1200                                 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1201                         }
1202                         final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1203                         for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1204                                 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1205                         }
1206                         // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1207                         for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1208                                 if (!(currentUserRolesToUpdate
1209                                                 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1210                                         HttpEntity<String> entity = new HttpEntity<>(headers);
1211                                         logger.debug(EELFLoggerDelegate.debugLogger,
1212                                                         "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1213                                                         userRole.getName());
1214                                         ResponseEntity<String> deleteResponse = template.exchange(
1215                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1216                                                                         + "userRole/" + name + "/" + userRole.getName(),
1217                                                         HttpMethod.DELETE, entity, String.class);
1218                                         logger.debug(EELFLoggerDelegate.debugLogger,
1219                                                         "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1220                                                         userRole.getName(), deleteResponse.getBody());
1221                                 }
1222                         }
1223                         // Check if user roles does not exists in External Central Auth System add them all
1224                         for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1225                                 if (!(currentUserRolesInExternalSystem
1226                                                 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1227                                         ExternalAccessUser extUser = new ExternalAccessUser(name,
1228                                                         app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1229                                         String formattedUserRole = mapper.writeValueAsString(extUser);
1230                                         HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1231                                         logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1232                                                         name , addUserRole.getRoleName());
1233                                         ResponseEntity<String> addResponse = template
1234                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1235                                                                         + "userRole", HttpMethod.POST, entity, String.class);
1236                                         logger.debug(EELFLoggerDelegate.debugLogger,
1237                                                         "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1238                                                         addResponse.getBody(), addUserRole.getRoleName());
1239                                         if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1240                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1241                                                                 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1242                                                                 addUserRole.getRoleName());
1243                                                 throw new Exception(addResponse.getBody());
1244                                         }
1245                                 }
1246                         }
1247                 } catch (HttpClientErrorException e) {
1248                         logger.error(EELFLoggerDelegate.errorLogger,
1249                                         "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1250                                         app.getId(), e);
1251                         if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1252                                 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1253                                 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1254                         }
1255                         if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1256                                 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1257                                 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1258                         }
1259                         EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1260                         throw e;
1261                 }
1262
1263                 catch (Exception e) {
1264                         logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1265                         EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1266                         throw e;
1267                 }
1268
1269         }
1270
1271         private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1272                         List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {             
1273                 Map<String, EPRole> epRoleList  = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);     
1274                 //Add Account Admin role for partner app to prevent conflict
1275                 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1276                 EPRole role =  new EPRole();
1277                 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1278                 epRoleList.put(role.getName(), role);
1279                 }
1280                 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));              
1281                 return userRoleDetailList;
1282         }
1283
1284         /**
1285          * 
1286          * @param userId
1287          * @param app
1288          * @param applicationsRestClientService
1289          * @param searchService
1290          * @param mapper
1291          * @throws Exception
1292          */
1293         protected void createNewUserOnRemoteApp(String userId, EPApp app,
1294                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1295                         ObjectMapper mapper, boolean postOpenSource) throws Exception {
1296
1297                         
1298                         EPUser client = searchService.searchUserByUserId(userId);
1299                         
1300                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1301                         
1302                         if (client == null) {
1303                                 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1304                                 logger.error(EELFLoggerDelegate.errorLogger, msg);
1305                                 throw new Exception(msg);
1306                         }
1307
1308                         client.setLoginId(userId);
1309                         client.setActive(true);
1310
1311                         String userInString = null;
1312                         userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1313                         logger.debug(EELFLoggerDelegate.debugLogger,
1314                                         "about to post new client to remote application, users json = " + userInString);
1315                         applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1316
1317         }
1318         
1319         @SuppressWarnings("unchecked")
1320         protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1321                 final Map<String, Long> epRequestParams = new HashMap<>();
1322                 try {
1323                         EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1324                         epAppRolesRequestData.setUpdatedDate(new Date());
1325                         epAppRolesRequestData.setRequestStatus(updateStatus);
1326                         HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1327                         addiotonalUpdateParam.put("userId", userId);
1328                         dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1329                         epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1330                         List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1331                         epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1332                                         epRequestParams, null);
1333                         if (epUserAppRolessDetailList.size() > 0) {
1334                                 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1335                                         EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1336                                         epAppRoleDetailData.setReqType(updateStatus);
1337                                         epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1338                                         HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1339                                         addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1340                                         dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1341                                 }
1342                         }
1343                         logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1344
1345                 } catch (Exception e) {
1346                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1347                 }
1348         }
1349         
1350         @SuppressWarnings("unchecked")
1351         public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1352                 final Map<String, Long> params = new HashMap<>();
1353                 final Map<String, Long> epDetailParams = new HashMap<>();
1354                 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1355                 params.put("appId", appId);
1356                 params.put("userId", user.getId());
1357                 try {
1358                         epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1359                                         .executeNamedQuery("userAppRolesRequestList", params, null);
1360                         if (epRequestIdVal.size() > 0) {
1361                                 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1362                                 epAppRolesRequestData.setUpdatedDate(new Date());
1363                                 epAppRolesRequestData.setRequestStatus("O");
1364                                 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1365                                 addiotonalUpdateParam.put("userId", user.getId());
1366                                 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1367                                 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1368                                 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1369                                 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1370                                                 epDetailParams, null);
1371                                 if (epUserAppRolesDetailList.size() > 0) {
1372                                         for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1373                                                 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1374                                                 epAppRoleDetailData.setReqType("O");
1375                                                 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1376                                                 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1377                                                 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1378                                                 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1379                                         }
1380                                         logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1381                                 }
1382                         }
1383
1384                 } catch (Exception e) {
1385                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1386                 }
1387         }
1388         
1389         /**
1390          * Pushes specified user details to the specified remote app.
1391          * 
1392          * @param userId
1393          *            OrgUserId identifying user at remote app in REST endpoint path
1394          * @param user
1395          *            User details to be pushed
1396          * @param app
1397          *            Remote app
1398          * @param applicationsRestClientService
1399          * @throws HTTPException
1400          */
1401         protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1402                         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1403         
1404                  getUser(userId, app, applicationsRestClientService);
1405                                         
1406         }
1407         
1408         /**
1409          * It returns user details for single org user id
1410          * 
1411          * @param userParams
1412          * @return
1413          *              if user exists it returns list of user details otherwise empty value
1414          */
1415         @SuppressWarnings("unchecked")
1416         private List<EPUser> checkIfUserExists(Map<String, String> userParams){ 
1417                 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1418         }
1419         
1420         /**
1421          * It checks whether the new user is valid or not otherwise throws exception
1422          * 
1423          * @param orgUserId
1424          * @param app
1425          * @return 
1426          *                      Checks if user is valid and returns message otherwise throws exception
1427          * @throws Exception
1428          */
1429         private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1430                 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1431                 if (epUser == null) {
1432                         throw new Exception("User does not exist");
1433                 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1434                         throw new Exception("User does not exist");
1435                 } else if (app == null) {
1436                         throw new Exception("Application does not exist");
1437                 }
1438                 return "Saved Successfully";
1439         }
1440         
1441         /**
1442          *   Checks if the fields exists or not
1443          *   
1444          * @param userList
1445          *                      contains user information
1446          * @param app
1447          *                      contains app name
1448          * @throws Exception
1449          *                      throws exception if the field is not valid
1450          */
1451         private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1452                 if (userList.size() == 0 || userList.isEmpty() ) {
1453                         throw new Exception("User does not exist");
1454                 } else if(app == null) {
1455                         throw new Exception("Application does not exist");
1456                 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1457                         throw new Exception(app.getMlAppName()+" application is unavailable");
1458                 }
1459         }
1460         
1461         @SuppressWarnings("unchecked")
1462         public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1463                 boolean result = false;
1464                 boolean externalSystemRequest = true;
1465                 final Map<String, Long> params = new HashMap<>();
1466                 final Map<String, String> userParams = new HashMap<>();
1467                 List<EPUser> userInfo = null;
1468                 EPUser user = null;
1469                 List<EPUserAppRolesRequest> epRequestId = null;
1470                 String orgUserId = "";
1471                 String updateStatus = "";
1472                 String reqMessage = "";
1473                 EPApp app = null;
1474                 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1475                         orgUserId = newAppRolesForUser.getLoginId().trim();
1476                 }
1477                 String appName = newAppRolesForUser.getApplicationName();
1478                 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1479                 if (orgUserId.length() > 0) {
1480                         ObjectMapper mapper = new ObjectMapper();
1481                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1482                         int epRequestIdSize = 0;
1483                         try {
1484                                 app = appsService.getAppDetail(appName);
1485                                 userParams.put("orgUserIdValue", orgUserId);
1486                                 userInfo = checkIfUserExists(userParams);
1487                                 reqMessage = "Updated Successfully";
1488                                 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1489                                         reqMessage = validateNewUser(orgUserId, app);
1490                                 }
1491                                 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1492                                         validateExternalRequestFields(userInfo, app);
1493                                         user = userInfo.get(0);
1494                                         params.put("appId", app.getId());
1495                                         params.put("userId", user.getId());
1496                                         epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1497                                                         .executeNamedQuery("userAppRolesRequestList", params, null);
1498                                         epRequestIdSize = epRequestId.size();
1499                                 }
1500                                 
1501                                 //If Non-Centralized app make sure you sync app roles before assigning to user
1502                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1503                                         logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1504                                         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1505                                         logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1506                                         if (appRoles.length > 0) {
1507                                                 syncAppRoles(sessionFactory, app.getId(), appRoles);
1508                                         }
1509                                 }
1510                                 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1511                                                 app.getId(), app.getMlAppName());
1512                                 List<EcompUserAppRoles> userRoleList = null;
1513                                 if(!userInfo.isEmpty()){
1514                                 final Map<String, Long> appParams = new HashMap<>();
1515                                 appParams.put("userId", user.getId());
1516                                 appParams.put("appId", app.getId());
1517                                 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1518                                 }
1519                                 // Check if list contains just account admin role
1520                                 boolean checkIfAdminRoleExists = false;
1521                                 if (reqType.equals("DELETE") && userRoleList!=null) {
1522                                         checkIfAdminRoleExists = userRoleList.stream()
1523                                                         .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1524                                 } else {
1525                                         checkIfAdminRoleExists = roleInAppForUserList.stream()
1526                                                         .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1527                                 }
1528                                 // if Centralized app
1529                                 if (app.getCentralAuth()) {
1530                                         // We should add If user does not exist in remote application
1531                                         try {
1532                                                 // If adding just account admin role dont make remote application user call or
1533                                                 // if request has only single non admin role then make remote call
1534                                                 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1535                                                                 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1536                                                                                 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1537                                                         // check if admin role exist then delete
1538                                                         List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1539                                                                           .collect(Collectors.toList());
1540                                                         remoteUserRoles.removeIf(role -> {
1541                                                                 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1542                                                         });
1543                                                         String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1544                                                         pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1545                                                                         applicationsRestClientService,true);
1546                                                 }
1547                                         } catch (Exception e) {
1548                                                 reqMessage = e.getMessage();
1549                                                 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1550                                                 throw new Exception(reqMessage);
1551                                         }
1552                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1553                                                         applicationsRestClientService, app.getId(), orgUserId);
1554                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1555                                                         userRolesInLocalApp);
1556                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1557                                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1558                                         // Apply changes in external Access system
1559                                         updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
1560                                         }
1561                                         logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1562                                                         newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1563                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1564                                 } 
1565                                 // If local application is not centralized 
1566                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1567                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1568                                                         applicationsRestClientService, app.getId(), orgUserId); 
1569                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1570                                                         userRolesInLocalApp);
1571                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1572                                 } else {// remote app
1573                                         // If adding just account admin role don't do remote application user call
1574                                         if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1575                                                 EPUser remoteAppUser = null;
1576                                                 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1577                                                 if (remoteAppUser == null) {
1578                                                         addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1579                                                                         applicationsRestClientService);
1580                                                         reqMessage = "Saved Successfully";
1581                                                 }
1582
1583                                                 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1584                                                                 applicationsRestClientService, app.getId(), orgUserId,false);
1585
1586                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1587                                                                 userRolesInRemoteApp);
1588                                                 logger.info(EELFLoggerDelegate.debugLogger,
1589                                                                 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1590                                                                 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1591                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1592                                                                 reqType,false);
1593                                                 // If no roles remain, request app to set user inactive.
1594                                                 /*
1595                                                  * if (userRolesInRemoteApp.size() == 0) {
1596                                                  * logger.debug(EELFLoggerDelegate.debugLogger,
1597                                                  * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1598                                                  * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1599                                                  * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1600                                                  * app, applicationsRestClientService); }
1601                                                  */
1602
1603                                         } else {
1604                                                 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote 
1605                                                 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1606                                                         reqMessage = "Saved Successfully";
1607                                                 }
1608                                                 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1609
1610                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1611                                                                 userRolesInRemoteApp);
1612                                                 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1613                                                                 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1614                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1615                                                                 reqType,false);
1616                                         }
1617                                         if(!result){
1618                                                 reqMessage = "Failed to save the user app role(s)";
1619                                         }
1620                                         if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1621                                                 updateStatus = "C";
1622                                                 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1623                                         }
1624                                 }
1625                         } catch (Exception e) {
1626                                 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1627                                                 orgUserId, appName);
1628                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1629                                 result = false;
1630                                 reqMessage = e.getMessage();
1631                                  if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1632                                  updateStatus = "F";
1633                                  applyChangesToAppRolesRequest(app.getId(), user.getId(),
1634                                  updateStatus, epRequestId.get(0));
1635                                  }
1636                         }
1637
1638                 }
1639                 return new ExternalRequestFieldsValidator(result, reqMessage);
1640         }
1641         
1642         /**
1643          * 
1644          * @param roleInAppForUserList
1645          * @param mapper
1646          * @param applicationsRestClientService
1647          * @param appId
1648          * @param userId
1649          * @return  Set<EcompRole>
1650          * @throws JsonProcessingException
1651          * @throws HTTPException
1652          */
1653         private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1654                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1655                         throws JsonProcessingException, HTTPException {
1656                 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1657                 return updatedUserRoles;
1658         }
1659         
1660         /**
1661          * It constructs and returns list of user app roles when the external API role approval system calls
1662          * this method
1663          * 
1664          * @param roleInAppForUserList
1665          * @param appId
1666          * @return list of user app roles
1667          * @throws Exception
1668          *                 throws exceptions if role id does not exits 
1669          */
1670         private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1671                         Long appId, String appName) throws Exception {
1672                 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1673                 EPRole existingAppRole = null;
1674                 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1675                         RoleInAppForUser ecompRole = new RoleInAppForUser();
1676                         existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1677                         if (existingAppRole == null) {
1678                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1679                                                 roleInAppForUserList);
1680                                 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1681                         }
1682                         if (!existingAppRole.getActive()) {
1683                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1684                                                 roleInAppForUserList);
1685                                 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1686                         } else {
1687                                 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1688                                 ecompRole.roleName = roleInAppForUser.getRoleName();
1689                                 ecompRole.isApplied = true;
1690                                 existingUserRoles.add(ecompRole);
1691                         }
1692                 }
1693                 return existingUserRoles;
1694         }
1695         
1696         
1697
1698         /**
1699          * 
1700          * @param userId
1701          * @param app
1702          * @param applicationsRestClientService
1703          * @return EPUser
1704          * @throws HTTPException
1705          */
1706         protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1707                         throws HTTPException {
1708                 // local app
1709                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1710                         // Map<String,String> params = new HashMap<String,String>();
1711                         // params.put("sbcid",userId);
1712                         @SuppressWarnings("unchecked")
1713                         List<EPUser> userList = (List<EPUser>) dataAccessService
1714                                         .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1715                         if (userList != null && !userList.isEmpty())
1716                                 return userList.get(0);
1717                         else
1718                                 return null;
1719                 }
1720                 // remote app
1721                 
1722                 return getUser(userId, app, applicationsRestClientService);
1723         }
1724         
1725         protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1726                         throws HTTPException {
1727                 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1728
1729         }
1730         
1731         protected boolean isAppUpgradeVersion(EPApp app){
1732                 return true;
1733         }
1734         
1735         
1736         public ExternalSystemAccess getExternalRequestAccess(){
1737                 ExternalSystemAccess res = null; 
1738                 try {
1739                         res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1740                                         Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1741                 } catch (Exception e) {
1742                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1743                 }
1744                 return res;             
1745         }
1746         
1747         /*
1748          * (non-Javadoc)
1749          * 
1750          * @see org.onap.portalapp.portal.service.UserRolesService#
1751          * getAppRolesForUser(java.lang.Long, java.lang.String)
1752          */
1753         @SuppressWarnings("unchecked")
1754         public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1755         List<RoleInAppForUser> rolesInAppForUser = null;
1756         EPApp app = appsService.getApp(appId);
1757         logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1758         try {
1759                 // for onap portal app, no need to make a remote call
1760                 List<Role> roleList = new ArrayList<>();
1761                 if (appId == PortalConstants.PORTAL_APP_ID) {           
1762                         if(app.getCentralAuth()){
1763                                 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1764                                 for(CentralV2Role cenRole : cenRoleList){
1765                                         Role role = new Role();
1766                                         role.setActive(cenRole.getActive());
1767                                         role.setId(cenRole.getId());
1768                                         role.setName(cenRole.getName());
1769                                         role.setPriority(cenRole.getPriority());
1770                                         roleList.add(role);
1771                                 }
1772                         }else{
1773                                 roleList = roleService.getAvailableRoles(userId);
1774                         }
1775                         List<Role> activeRoleList = new ArrayList<Role>();
1776                         for(Role role: roleList) {
1777                                 if(role.getActive()) {
1778                                         if(role.getId() != 1){ // prevent portal admin from being added
1779                                                 activeRoleList.add(role);
1780                                         } else if(extRequestValue){
1781                                                 activeRoleList.add(role);
1782                                         }
1783                                 }
1784                                         
1785                         }
1786                         EPUser localUser  = getUserFromApp(userId, app, applicationsRestClientService);
1787                         // If localUser does not exists return roles
1788                         Set<EPRole> roleSet = null;
1789                         EPRole[] roleSetList = null;
1790                         if(localUser != null){
1791                                 roleSet = localUser.getAppEPRoles(app);
1792                                 roleSetList = roleSet.toArray(new EPRole[0]);
1793                         }
1794                         rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1795                         return rolesInAppForUser;
1796                 }
1797                 
1798                 EcompRole[] appRoles = null;
1799                 List<EcompRole> roles = new ArrayList<>();
1800                         if (app.getCentralAuth()) {
1801                                 final Map<String, Long> appParams = new HashMap<>();
1802                                 appParams.put("appId", app.getId());
1803                                 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1804                                                 appParams, null);
1805
1806                                 EPApp application = appService.getApp(appId);
1807                                 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1808                                                 application);
1809
1810                                 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1811                                 for (EPRole role : applicationRoles) {
1812                                         Map<String, Long> params = new HashMap<>();
1813                                         params.put("roleId", role.getId());
1814                                         params.put(APP_ID, app.getId());
1815                                         List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1816                                                         .executeNamedQuery("getAppRoleFunctionList", params, null);
1817
1818                                         // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1819                                         // new TreeSet<>();
1820                                         SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1821                                         for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1822
1823                                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1824                                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1825                                                 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1826                                                 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1827                                                 String name = roleFunc.getName();
1828
1829                                                 RoleFunction function = new RoleFunction();
1830                                                 function.setAction(action);
1831                                                 function.setType(type);
1832                                                 function.setCode(functionCode);
1833                                                 function.setName(name);
1834                                                 roleFunctionSet.add(function);
1835                                                 role.setRoleFunctions(roleFunctionSet);
1836
1837                                         }
1838                                         rolesetwithfunctioncds.add(role);
1839
1840
1841                                 }
1842
1843                                 for (EPRole role1 : rolesetwithfunctioncds) {
1844                                         EcompRole ecompRole = new EcompRole();
1845                                         ecompRole.setId(role1.getId());
1846                                         ecompRole.setName(role1.getName());
1847                                         ecompRole.setRoleFunctions(role1.getRoleFunctions());
1848                                         roles.add(ecompRole);
1849
1850                                 }
1851                                         if (checkIfUserisApplicationAccAdmin) {
1852                                         appRoles = roles.toArray(new EcompRole[roles.size()]);
1853                                         logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1854                                 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1855                                         List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1856                                         List<String> roleAdminAppRolesNames = new ArrayList<>();
1857                                         final Map<String, Long> userParams = new HashMap<>();
1858                                         userParams.put("userId", user.getId()); 
1859                                         List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1860
1861                                         List<EcompRole> userapproverRolesList = new ArrayList<>();
1862                                         for (String str : getUserApproverRoles) {
1863                                                 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1864                                                 if (epRole != null)
1865                                                         userapproverRolesList.add(epRole);
1866                                         }
1867 //                                      roles.removeAll(userapproverRolesList);
1868                                         for (EcompRole role : userapproverRolesList) {
1869
1870                                                 List<RoleFunction> roleFunList = new ArrayList<>();
1871                                                 roleFunList.addAll(role.getRoleFunctions());
1872                                                 boolean checkIfFunctionsExits = roleFunList.stream()
1873                                                                 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1874                                                 if (checkIfFunctionsExits) {
1875                                                         roleAdminAppRoles.add(role);
1876                                                         List<RoleFunction> filteredList = roleFunList.stream()
1877                                                                         .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1878                                                         roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1879                                                                         .collect(Collectors.toList()));
1880 //                                                      roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
1881 //                                                                      .collect(Collectors.toList());
1882                                                 }
1883                                         }
1884                                                 for (String name : roleAdminAppRolesNames) {
1885                                                         EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
1886                                                                         .orElse(null);
1887                                                         if (ecompRole != null)
1888                                                                 roleAdminAppRoles.add(ecompRole);
1889                                                 
1890                                         }
1891                                         appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
1892
1893                                 }
1894                         } else{
1895                         appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1896                 }
1897                 // Test this error case, for generating an internal ONAP Portal
1898                 // error
1899                 // EcompRole[] appRoles = null;
1900                 // If there is an exception in the rest client api, then null will
1901                 // be returned.
1902                 if (appRoles != null) {
1903                         if(!app.getCentralAuth()) {
1904                         syncAppRoles(sessionFactory, appId, appRoles);
1905                         }
1906                         EcompRole[] userAppRoles = null;
1907                         try {
1908                                 try {
1909                                         
1910                                         if(app.getCentralAuth()){
1911                                                 final Map<String, String> params = new HashMap<>();
1912                                                 final Map<String, Long> userParams = new HashMap<>();
1913                                                 params.put("orgUserIdValue", userId);
1914                                                 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1915                                                 userParams.put("appId", app.getId());
1916                                                 userParams.put("userId", actualUser.get(0).getId());    
1917                                                 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1918                                                         
1919                                                 List<EcompRole> setUserRoles = new ArrayList<>();
1920                                                         for(EPUserAppCurrentRoles role : userAppsRolesList){
1921                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1922                                                                 EcompRole ecompRole = new EcompRole();
1923                                                                 ecompRole.setId(role.getRoleId());
1924                                                                 ecompRole.setName(role.getRoleName());
1925                                                                 setUserRoles.add(ecompRole);
1926                                                         }
1927                                                 
1928                                                         boolean checkIfUserisAccAdmin = setUserRoles.stream()
1929                                                                         .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1930                                                         
1931                                                 if (!checkIfUserisAccAdmin) {
1932                                                         List<EcompRole> userApplicationRolesList = setUserRoles;
1933                                                         List<EcompRole> appRolesList = Arrays.asList(appRoles);
1934                                                          Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1935
1936                                                         List<String> roleNames = new ArrayList<>();
1937                                                                 for (EcompRole role : userApplicationRolesList) {
1938                                                                         EcompRole epRole = appRolesList.stream()
1939                                                                                         .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1940                                                                         List<RoleFunction> roleFunList = new ArrayList<>();
1941                                                                         if(epRole.getRoleFunctions().size()>0)
1942                                                                         roleFunList.addAll(epRole.getRoleFunctions());
1943                                                                         boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1944                                                                                         roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1945                                                                         if (checkIfFunctionsExits) {
1946                                                                                 finalUserAppRolesList.add(role);
1947                                                                                 List<RoleFunction> filteredList = roleFunList.stream()
1948                                                                                                 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1949                                                                                                 .collect(Collectors.toList());
1950                                                                                 roleNames = filteredList.stream().map(RoleFunction::getCode)
1951                                                                                                 .collect(Collectors.toList());
1952                                                                         }
1953
1954                                                                         for (String name : roleNames) {
1955                                                                                 EcompRole ecompRole = appRolesList.stream()
1956                                                                                                 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1957                                                                                 if (ecompRole != null)
1958                                                                                         finalUserAppRolesList.add(ecompRole);
1959                                                                         }
1960                                                                 }
1961                                                                 
1962                                                                 
1963                                                         for (String name : roleNames) {
1964                                                                 
1965                                                                 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1966                                                                                 role -> role.getRoleName().equalsIgnoreCase(name));             
1967                                                                 if(checkIfFunctionsExits)
1968                                                                 {
1969                                                                         EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
1970                                                                                         .findAny().orElse(null);
1971                                                                         if(epRole != null)
1972                                                                         setUserRoles.add(epRole);
1973                                                                 }
1974                                                                 
1975                                                         }
1976                                                         userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1977                                                 } 
1978                                         }else{
1979                                                 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1980                                                                 String.format("/user/%s/roles", userId));
1981                                         }
1982                                 } catch (HTTPException e) {
1983                                         // Some apps are returning 400 if user is not found.
1984                                         if (e.getResponseCode() == 400) {
1985                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1986                                                                 "getAppRolesForUser caught exception with response code 400; continuing", e);
1987                                         } else {
1988                                                 // Other response code, let it come thru.
1989                                                 throw e;
1990                                         }
1991                                 }
1992                                 if (userAppRoles == null) {
1993                                         if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1994                                                 EcompPortalUtils.setExternalAppResponseCode(200);
1995                                                 String message = String.format(
1996                                                                 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1997                                                                                 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1998                                                                                 + "Overriding to 200 until framework SDK returns a useful response.",
1999                                                                 Long.toString(appId), userId);
2000                                                 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2001                                         }
2002                                 }
2003                                 
2004                                  HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2005                                         ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2006                                         if(userAppRoles != null){
2007                                                 for (int i = 0; i < userAppRoles.length; i++) {
2008                                                         if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2009                                                                 EcompRole role = new EcompRole();
2010                                                                 role.setId(userAppRoles[i].getId());
2011                                                                 role.setName(userAppRoles[i].getName());
2012                                                                 activeRoles.add(role);
2013                                                         }
2014                                                 }
2015                                         }
2016                                         EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2017                                 
2018                                 // If the remote application isn't down we MUST sync user
2019                                 // roles here in case we have this user here!
2020                                 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
2021                         } catch (Exception e) {
2022                                 // TODO: we may need to check if user exists, maybe remote
2023                                 // app is down.
2024                                 String message = String.format(
2025                                                 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2026                                                 Long.toString(appId));
2027                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2028                                 userAppRoles = new EcompRole[0];
2029                         }
2030                         rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2031                 }
2032         } catch (Exception e) {
2033                 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2034                                 Long.toString(appId));
2035                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2036         }
2037         return rolesInAppForUser;
2038         }
2039         
2040         private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2041                         ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2042                         throws JsonProcessingException, HTTPException {
2043                 boolean result = false;
2044                 ObjectMapper mapper = new ObjectMapper();
2045                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2046                 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2047                 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2048                 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2049                 return result;
2050         }
2051
2052         @SuppressWarnings("unchecked")
2053         public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2054                 FieldsValidator fieldsValidator = new FieldsValidator();
2055                 final Map<String, Long> params = new HashMap<>();
2056                 List<EPUserAppRoles>  appRole= null;
2057                 try {
2058                         logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2059                         boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
2060                         logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2061                                                 
2062                         params.put("appId", userAppRolesData.appId);
2063                         EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2064                         epAppRolesRequestData.setCreatedDate(new Date());
2065                         epAppRolesRequestData.setUpdatedDate(new Date());
2066                         epAppRolesRequestData.setUserId(user.getId());
2067                         epAppRolesRequestData.setAppId(userAppRolesData.appId);
2068                         epAppRolesRequestData.setRequestStatus("P");
2069                         List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
2070                         Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2071                         dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2072                         for (RoleInAppForUser userAppRoles : appRoleIdList) {
2073                                 Boolean isAppliedVal = userAppRoles.isApplied;
2074                                 params.put("appRoleId", userAppRoles.roleId);                           
2075                                 if (isAppliedVal) {
2076                                         appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2077                                         if (!appRole.isEmpty()) {
2078                                                 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2079                                                 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2080                                                 epAppRoleDetail.setReqType("P");
2081                                                 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2082                                                 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2083                                         }
2084                                 }                       
2085                         }
2086                         epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2087                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2088
2089                 } catch (Exception e) {
2090                         logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2091                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2092                 }
2093                 return fieldsValidator;
2094         }
2095
2096         public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {      
2097                 Map<String, String> params = new HashMap<>();
2098                 params.put("userid", userid.getId().toString());
2099                 //params.put("appid", appid);
2100                 params.put("appName", appName);
2101                         
2102                 @SuppressWarnings("unchecked")
2103                 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2104                                 .executeNamedQuery("userAppCatalogRoles", params, null);
2105                 return userAppRoles;    
2106         }
2107         
2108         public String updateRemoteUserProfile(String orgUserId, Long appId) {
2109                 ObjectMapper mapper = new ObjectMapper();
2110                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2111                 EPUser client = searchService.searchUserByUserId(orgUserId);
2112                 EPUser newUser = new EPUser();
2113                 newUser.setActive(client.getActive());
2114                 newUser.setFirstName(client.getFirstName());
2115                 newUser.setLastName(client.getLastName());
2116                 newUser.setLoginId(client.getLoginId());
2117                 newUser.setLoginPwd(client.getLoginPwd());
2118                 newUser.setMiddleInitial(client.getMiddleInitial());
2119                 newUser.setEmail(client.getEmail());
2120                 newUser.setOrgUserId(client.getLoginId());
2121                 try {
2122                         String userAsString = mapper.writeValueAsString(newUser);
2123                         List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2124                         // applicationsRestClientService.post(EPUser.class, appId,
2125                         // userAsString, String.format("/user", orgUserId));
2126                         for (EPApp eachApp : appList) {
2127                                 try {
2128                                         applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2129                                                         String.format("/user/%s", orgUserId));
2130                                 } catch (Exception e) {
2131                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2132                                                         + " in remote app. appId = " + eachApp.getId());
2133                                 }
2134                         }
2135                 } catch (Exception e) {
2136                         logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2137                         return "failure";
2138                 }
2139
2140                 return "success";
2141         }
2142
2143
2144         /*
2145          * (non-Javadoc)
2146          * 
2147          * @see org.onap.portalapp.portal.service.UserRolesService#
2148          * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2149          */
2150         @SuppressWarnings("deprecation")
2151         public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2152                 // Find the records for this user-app combo, if any
2153                 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2154                 @SuppressWarnings("unchecked")
2155                 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2156                 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2157                 return roleList;
2158         }
2159         
2160         /**
2161          * It retrieves and returns list of user app roles for local and remote applications based app id
2162          * 
2163          * @param appId
2164          * @return list of user app roles
2165          * @throws HTTPException 
2166          */
2167         public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2168                 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2169                 
2170                 EPApp app = appsService.getApp(appId);
2171                 //If local or centralized application
2172                 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2173                         @SuppressWarnings("unchecked")
2174                         List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2175                         for (EPUser user : userList) {
2176                                 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2177                                 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2178                                         userApplicationRoles.add(userWithAppRoles);
2179                         }
2180
2181                 } 
2182                 // remote app
2183                 else {  
2184                         RemoteUserWithRoles[] remoteUsers = null;
2185                         String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2186                         
2187                         remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2188                         
2189                         userApplicationRoles = new ArrayList<UserApplicationRoles>();
2190                         for (RemoteUserWithRoles remoteUser : remoteUsers) {
2191                                 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2192                                 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2193                                         userApplicationRoles.add(userWithRemoteAppRoles);
2194                                 } else {
2195                                         logger.debug(EELFLoggerDelegate.debugLogger,
2196                                                         "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2197                                 }
2198                         }
2199                 }
2200                 
2201                 return userApplicationRoles;
2202         }
2203         
2204         /**
2205          * 
2206          * @param appId
2207          * @param user
2208          * @param appgetUsersFromAppEndpoint
2209          * @return
2210          */
2211         private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2212                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2213                 userWithRemoteAppRoles.setAppId(appId);
2214                 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2215                 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2216                 userWithRemoteAppRoles.setLastName(user.getLastName());
2217                 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2218                 return userWithRemoteAppRoles;
2219         }
2220
2221         /**
2222          * 
2223          * @param user
2224          * @param app
2225          * @return
2226          */
2227         @SuppressWarnings("unchecked")
2228         private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2229                 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2230                 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2231                 for (EPRole role : roleSet) {
2232                         logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2233                         RemoteRole rRole = new RemoteRole();
2234                         rRole.setId(role.getId());
2235                         rRole.setName(role.getName());
2236                         roleList.add(rRole);
2237                 }
2238                 
2239                 //Get the active roles of user for that application using query
2240                 List<EPRole> userEpRoleList = new ArrayList<>();
2241                 final Map<String, Long> params = new HashMap<>();
2242                 params.put("appId", app.getId());
2243                 params.put("userId", user.getId());
2244                 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2245
2246                 for (EPRole remoteUserRoleList : userEpRoleList) {
2247
2248                         RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2249                                         .findAny().orElse(null);
2250                         if (remoteRoleListId == null) {
2251                                 logger.debug(EELFLoggerDelegate.debugLogger,
2252                                                 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2253
2254                                                 remoteUserRoleList.getName());
2255                                 RemoteRole role = new RemoteRole();
2256                                 role.setId(remoteUserRoleList.getId());
2257                                 role.setName(remoteUserRoleList.getName());
2258
2259                                 roleList.add(role);
2260                         }
2261
2262                 }
2263
2264                 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2265
2266                 return roleList;
2267                 
2268                 
2269                 
2270         }
2271
2272         public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2273
2274                 ObjectMapper mapper = new ObjectMapper();
2275                 try {
2276                         return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2277                 } catch (IOException e) {
2278                         logger.error(EELFLoggerDelegate.errorLogger,
2279                                         "doGetUsers : Failed : Unexpected property in incoming JSON",
2280                                         e);
2281                         logger.error(EELFLoggerDelegate.errorLogger,
2282                                         "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2283                 }
2284
2285                 return new RemoteUserWithRoles[0];
2286         }
2287
2288         @SuppressWarnings("unchecked")
2289         public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2290                 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2291                 final Map<String, Long> params = new HashMap<>();
2292                 params.put("appId", appId);
2293                 params.put("userId", userId);
2294                 params.put("roleId", roleId);
2295                 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2296                 return userRoleList;
2297         }
2298         
2299         
2300         /*public static void main(String[] args) {
2301                 List<EcompRole> str1 = new ArrayList<String>();
2302                 str1.add("A");
2303                 str1.add("B");
2304                 str1.add("C");
2305                 str1.add("D");
2306
2307                 List<String> str2 = new ArrayList<String>();
2308                 str2.add("D");
2309                 str2.add("E");
2310
2311                 List<EcompRole> userApplicationRolesList = setUserRoles;
2312                 List<EcompRole> appRolesList = Arrays.asList(appRoles);
2313                 
2314         }*/
2315 }