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