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