Onboarding Page Account Admin Change
[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) 2019 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.isSystemUser();
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 isSystemUser,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, isSystemUser);
1204                         }
1205                         String name = "";
1206                         if (EPCommonSystemProperties
1207                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
1208                                 name = orgUserId
1209                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1210                         } else {
1211                                 name = orgUserId;
1212                         }
1213                         ObjectMapper mapper = new ObjectMapper();
1214                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1215                         HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1216                         ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1217
1218                         
1219                         List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1220                         String res = getResponse.getBody();
1221                         JSONObject jsonObj = null;
1222                         JSONArray extRoles = null;
1223                         if (!res.equals("{}")) {
1224                                 jsonObj = new JSONObject(res);
1225                                 extRoles = jsonObj.getJSONArray("role");
1226                         }
1227                         ExternalAccessUserRoleDetail userRoleDetail = null;
1228                         if (extRoles != null) {
1229                                 for (int i = 0; i < extRoles.length(); i++) {
1230                                         if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1231                                                         && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1232                                                         && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1233                                                 if (extRoles.getJSONObject(i).has("description")) {
1234                                                         ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1235                                                         userRoleDetail = new ExternalAccessUserRoleDetail(
1236                                                                         extRoles.getJSONObject(i).getString("name"), desc);
1237                                                         userRoleDetailList.add(userRoleDetail);
1238                                                 } else {
1239                                                         userRoleDetail = new ExternalAccessUserRoleDetail(
1240                                                                         extRoles.getJSONObject(i).getString("name"), null);
1241                                                         userRoleDetailList.add(userRoleDetail);
1242                                                 }
1243
1244                                         }
1245                                 }
1246                         }
1247                         
1248                         List<ExternalAccessUserRoleDetail>  userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1249                         
1250                         List<EcompUserAppRoles> userAppList = new ArrayList<>();
1251                         // If request coming from portal not from external role approval system then we have to check if user already 
1252                         // have account admin or system admin as GUI will not send these roles 
1253                         if (!isPortalRequest) {
1254                                 final Map<String, String> loginIdParams = new HashMap<>();
1255                                 loginIdParams.put("orgUserIdValue", orgUserId);
1256                                 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1257                                 final Map<String, Long> params = new HashMap<>();
1258                                 params.put("appId", app.getId());
1259                                 params.put("userId", user.getId());
1260                                  userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1261                                                 params, null);
1262                                 if (!roleInAppUser.isEmpty()) {
1263                                         for (EcompUserAppRoles userApp : userAppList) {
1264                                                 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1265                                                                 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1266                                                         RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1267                                                         addSpecialRole.setIsApplied(true);
1268                                                         addSpecialRole.setRoleId(userApp.getRoleId());
1269                                                         addSpecialRole.setRoleName(userApp.getRoleName());
1270                                                         roleInAppUser.add(addSpecialRole);
1271                                                 }
1272                                         }
1273                                 }
1274                         }
1275                         List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1276                                         .collect(Collectors.toList());
1277                          Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1278                         for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1279                                 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1280                         }
1281                         final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1282                         for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1283                                 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1284                         }
1285
1286                         if (isLoggedInUserRoleAdminofApp) {
1287                                 if (deletedRolesByApprover.size() > 0) {
1288                                         List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
1289                                         Set<EcompRole> roles = new HashSet<>();
1290                                         for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1291                                                 for (EcompRole role : deletedRolesByApprover) {
1292                                                         if ((userRole.getName().substring(app.getNameSpace().length() + 1)).equals(role.getName())) {
1293                                                                 roles.add(role);
1294                                                                 newUpdatedRoles.add(userRole);
1295                                                         }
1296                                                 }
1297                                         }
1298                                         if (newUpdatedRoles.size() > 0) {
1299                                                 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1300                                                 userRoleListMatchingInExtAuthAndLocal.addAll(newUpdatedRoles);
1301                                         } else {
1302                                                 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1303                                                 currentUserRolesToUpdate = new HashMap<>();
1304
1305                                         }
1306
1307                                 } else {
1308                                         userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1309                                         currentUserRolesToUpdate = new HashMap<>();
1310
1311                                 }
1312                         }
1313
1314                         // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1315                         for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1316                                 if (!(currentUserRolesToUpdate
1317                                                 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1318                                         HttpEntity<String> entity = new HttpEntity<>(headers);
1319                                         logger.debug(EELFLoggerDelegate.debugLogger,
1320                                                         "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1321                                                         userRole.getName());
1322                                         ResponseEntity<String> deleteResponse = template.exchange(
1323                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1324                                                                         + "userRole/" + name + "/" + userRole.getName(),
1325                                                         HttpMethod.DELETE, entity, String.class);
1326                                         logger.debug(EELFLoggerDelegate.debugLogger,
1327                                                         "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1328                                                         userRole.getName(), deleteResponse.getBody());
1329                                 }
1330                         }
1331                         // Check if user roles does not exists in External Central Auth System add them all
1332                         for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1333                                 if (!(currentUserRolesInExternalSystem
1334                                                 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1335                                         ExternalAccessUser extUser = new ExternalAccessUser(name,
1336                                                         app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1337                                         String formattedUserRole = mapper.writeValueAsString(extUser);
1338                                         HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1339                                         logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1340                                                         name , addUserRole.getRoleName());
1341                                         ResponseEntity<String> addResponse = template
1342                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1343                                                                         + "userRole", HttpMethod.POST, entity, String.class);
1344                                         logger.debug(EELFLoggerDelegate.debugLogger,
1345                                                         "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1346                                                         addResponse.getBody(), addUserRole.getRoleName());
1347                                         if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1348                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1349                                                                 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1350                                                                 addUserRole.getRoleName());
1351                                                 throw new Exception(addResponse.getBody());
1352                                         }
1353                                 }
1354                         }
1355                 } catch (HttpClientErrorException e) {
1356                         logger.error(EELFLoggerDelegate.errorLogger,
1357                                         "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1358                                         app.getId(), e);
1359                         if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1360                                 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1361                                 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1362                         }
1363                         if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1364                                 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1365                                 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1366                         }
1367                         EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1368                         throw e;
1369                 }
1370
1371                 catch (Exception e) {
1372                         logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1373                         EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1374                         throw e;
1375                 }
1376
1377         }
1378
1379         private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1380                         List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {             
1381                 Map<String, EPRole> epRoleList  = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);     
1382                 //Add Account Admin role for partner app to prevent conflict
1383                 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1384                 EPRole role =  new EPRole();
1385                 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1386                 epRoleList.put(role.getName(), role);
1387                 }
1388                 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));              
1389                 return userRoleDetailList;
1390         }
1391
1392         /**
1393          * 
1394          * @param userId
1395          * @param app
1396          * @param applicationsRestClientService
1397          * @param searchService
1398          * @param mapper
1399          * @throws Exception
1400          */
1401         protected void createNewUserOnRemoteApp(String userId, EPApp app,
1402                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1403                         ObjectMapper mapper, boolean postOpenSource) throws Exception {
1404
1405                         
1406                         EPUser client = searchService.searchUserByUserId(userId);
1407                         
1408                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1409                         
1410                         if (client == null) {
1411                                 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1412                                 logger.error(EELFLoggerDelegate.errorLogger, msg);
1413                                 throw new Exception(msg);
1414                         }
1415
1416                         client.setLoginId(userId);
1417                         client.setActive(true);
1418
1419                         String userInString = null;
1420                         userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1421                         logger.debug(EELFLoggerDelegate.debugLogger,
1422                                         "about to post new client to remote application, users json = " + userInString);
1423                         applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1424
1425         }
1426         
1427         @SuppressWarnings("unchecked")
1428         protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1429                 final Map<String, Long> epRequestParams = new HashMap<>();
1430                 try {
1431                         EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1432                         epAppRolesRequestData.setUpdatedDate(new Date());
1433                         epAppRolesRequestData.setRequestStatus(updateStatus);
1434                         HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1435                         addiotonalUpdateParam.put("userId", userId);
1436                         dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1437                         epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1438                         List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1439                         epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1440                                         epRequestParams, null);
1441                         if (epUserAppRolessDetailList.size() > 0) {
1442                                 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1443                                         EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1444                                         epAppRoleDetailData.setReqType(updateStatus);
1445                                         epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1446                                         HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1447                                         addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1448                                         dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1449                                 }
1450                         }
1451                         logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1452
1453                 } catch (Exception e) {
1454                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1455                 }
1456         }
1457         
1458         @SuppressWarnings("unchecked")
1459         public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1460                 final Map<String, Long> params = new HashMap<>();
1461                 final Map<String, Long> epDetailParams = new HashMap<>();
1462                 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1463                 params.put("appId", appId);
1464                 params.put("userId", user.getId());
1465                 try {
1466                         epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1467                                         .executeNamedQuery("userAppRolesRequestList", params, null);
1468                         if (epRequestIdVal.size() > 0) {
1469                                 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1470                                 epAppRolesRequestData.setUpdatedDate(new Date());
1471                                 epAppRolesRequestData.setRequestStatus("O");
1472                                 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1473                                 addiotonalUpdateParam.put("userId", user.getId());
1474                                 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1475                                 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1476                                 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1477                                 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1478                                                 epDetailParams, null);
1479                                 if (epUserAppRolesDetailList.size() > 0) {
1480                                         for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1481                                                 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1482                                                 epAppRoleDetailData.setReqType("O");
1483                                                 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1484                                                 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1485                                                 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1486                                                 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1487                                         }
1488                                         logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1489                                 }
1490                         }
1491
1492                 } catch (Exception e) {
1493                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1494                 }
1495         }
1496         
1497         /**
1498          * Pushes specified user details to the specified remote app.
1499          * 
1500          * @param userId
1501          *            OrgUserId identifying user at remote app in REST endpoint path
1502          * @param user
1503          *            User details to be pushed
1504          * @param app
1505          *            Remote app
1506          * @param applicationsRestClientService
1507          * @throws HTTPException
1508          */
1509         protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1510                         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1511         
1512                  getUser(userId, app, applicationsRestClientService);
1513                                         
1514         }
1515         
1516         /**
1517          * It returns user details for single org user id
1518          * 
1519          * @param userParams
1520          * @return
1521          *              if user exists it returns list of user details otherwise empty value
1522          */
1523         @SuppressWarnings("unchecked")
1524         private List<EPUser> checkIfUserExists(Map<String, String> userParams){ 
1525                 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1526         }
1527         
1528         /**
1529          * It checks whether the new user is valid or not otherwise throws exception
1530          * 
1531          * @param orgUserId
1532          * @param app
1533          * @return 
1534          *                      Checks if user is valid and returns message otherwise throws exception
1535          * @throws Exception
1536          */
1537         private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1538                 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1539                 if (epUser == null) {
1540                         throw new Exception("User does not exist");
1541                 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1542                         throw new Exception("User does not exist");
1543                 } else if (app == null) {
1544                         throw new Exception("Application does not exist");
1545                 }
1546                 return "Saved Successfully";
1547         }
1548         
1549         /**
1550          *   Checks if the fields exists or not
1551          *   
1552          * @param userList
1553          *                      contains user information
1554          * @param app
1555          *                      contains app name
1556          * @throws Exception
1557          *                      throws exception if the field is not valid
1558          */
1559         private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1560                 if (userList.size() == 0 || userList.isEmpty() ) {
1561                         throw new Exception("User does not exist");
1562                 } else if(app == null) {
1563                         throw new Exception("Application does not exist");
1564                 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1565                         throw new Exception(app.getMlAppName()+" application is unavailable");
1566                 }
1567         }
1568         
1569         @SuppressWarnings("unchecked")
1570         public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1571                 boolean result = false;
1572                 boolean externalSystemRequest = true;
1573                 final Map<String, Long> params = new HashMap<>();
1574                 final Map<String, String> userParams = new HashMap<>();
1575                 List<EPUser> userInfo = null;
1576                 EPUser user = null;
1577                 List<EPUserAppRolesRequest> epRequestId = null;
1578                 String orgUserId = "";
1579                 String updateStatus = "";
1580                 String reqMessage = "";
1581                 EPApp app = null;
1582                 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1583                         orgUserId = newAppRolesForUser.getLoginId().trim();
1584                 }
1585                 String appName = newAppRolesForUser.getApplicationName();
1586                 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1587                 if (orgUserId.length() > 0) {
1588                         ObjectMapper mapper = new ObjectMapper();
1589                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1590                         int epRequestIdSize = 0;
1591                         try {
1592                                 app = appsService.getAppDetail(appName);
1593                                 userParams.put("orgUserIdValue", orgUserId);
1594                                 userInfo = checkIfUserExists(userParams);
1595                                 reqMessage = "Updated Successfully";
1596                                 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1597                                         reqMessage = validateNewUser(orgUserId, app);
1598                                 }
1599                                 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1600                                         validateExternalRequestFields(userInfo, app);
1601                                         user = userInfo.get(0);
1602                                         params.put("appId", app.getId());
1603                                         params.put("userId", user.getId());
1604                                         epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1605                                                         .executeNamedQuery("userAppRolesRequestList", params, null);
1606                                         epRequestIdSize = epRequestId.size();
1607                                 }
1608                                 
1609                                 //If Non-Centralized app make sure you sync app roles before assigning to user
1610                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1611                                         logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1612                                         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1613                                         logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1614                                         if (appRoles.length > 0) {
1615                                                 syncAppRoles(sessionFactory, app.getId(), appRoles);
1616                                         }
1617                                 }
1618                                 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1619                                                 app.getId(), app.getMlAppName());
1620                                 List<EcompUserAppRoles> userRoleList = null;
1621                                 if(!userInfo.isEmpty()){
1622                                 final Map<String, Long> appParams = new HashMap<>();
1623                                 appParams.put("userId", user.getId());
1624                                 appParams.put("appId", app.getId());
1625                                 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1626                                 }
1627                                 // Check if list contains just account admin role
1628                                 boolean checkIfAdminRoleExists = false;
1629                                 if (reqType.equals("DELETE") && userRoleList!=null) {
1630                                         checkIfAdminRoleExists = userRoleList.stream()
1631                                                         .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1632                                 } else {
1633                                         checkIfAdminRoleExists = roleInAppForUserList.stream()
1634                                                         .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1635                                 }
1636                                 // if Centralized app
1637                                 if (app.getCentralAuth()) {
1638                                         // We should add If user does not exist in remote application
1639                                         try {
1640                                                 // If adding just account admin role dont make remote application user call or
1641                                                 // if request has only single non admin role then make remote call
1642                                                 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1643                                                                 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1644                                                                                 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1645                                                         // check if admin role exist then delete
1646                                                         List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1647                                                                           .collect(Collectors.toList());
1648                                                         remoteUserRoles.removeIf(role -> {
1649                                                                 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1650                                                         });
1651                                                         String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1652                                                         pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1653                                                                         applicationsRestClientService,true);
1654                                                 }
1655                                         } catch (Exception e) {
1656                                                 reqMessage = e.getMessage();
1657                                                 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1658                                                 throw new Exception(reqMessage);
1659                                         }
1660                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1661                                                         applicationsRestClientService, app.getId(), orgUserId);
1662                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1663                                                         userRolesInLocalApp);
1664                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1665                                         Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1666
1667                                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1668                                         // Apply changes in external Access system
1669                                         updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false,rolesGotDeletedByApprover,false);
1670                                         }
1671                                         logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1672                                                         newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1673                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false);
1674                                 } 
1675                                 // If local application is not centralized 
1676                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1677                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1678                                                         applicationsRestClientService, app.getId(), orgUserId); 
1679                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1680                                                         userRolesInLocalApp);
1681                                         Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1682
1683                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false);
1684                                 } else {// remote app
1685                                         // If adding just account admin role don't do remote application user call
1686                                         if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1687                                                 EPUser remoteAppUser = null;
1688                                                 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1689                                                 if (remoteAppUser == null) {
1690                                                         addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1691                                                                         applicationsRestClientService);
1692                                                         reqMessage = "Saved Successfully";
1693                                                 }
1694
1695                                                 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1696                                                                 applicationsRestClientService, app.getId(), orgUserId,false);
1697
1698                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1699                                                                 userRolesInRemoteApp);
1700                                                 logger.info(EELFLoggerDelegate.debugLogger,
1701                                                                 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1702                                                                 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1703                                                 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1704
1705                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1706                                                                 reqType,false,rolesGotDeletedByApprover,false);
1707                                                 // If no roles remain, request app to set user inactive.
1708                                                 /*
1709                                                  * if (userRolesInRemoteApp.size() == 0) {
1710                                                  * logger.debug(EELFLoggerDelegate.debugLogger,
1711                                                  * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1712                                                  * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1713                                                  * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1714                                                  * app, applicationsRestClientService); }
1715                                                  */
1716
1717                                         } else {
1718                                                 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote 
1719                                                 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1720                                                         reqMessage = "Saved Successfully";
1721                                                 }
1722                                                 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1723
1724                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1725                                                                 userRolesInRemoteApp);
1726                                                 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1727                                                                 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1728                                                 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1729
1730                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1731                                                                 reqType,false,rolesGotDeletedByApprover,false);
1732                                         }
1733                                         if(!result){
1734                                                 reqMessage = "Failed to save the user app role(s)";
1735                                         }
1736                                         if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1737                                                 updateStatus = "C";
1738                                                 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1739                                         }
1740                                 }
1741                         } catch (Exception e) {
1742                                 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1743                                                 orgUserId, appName);
1744                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1745                                 result = false;
1746                                 reqMessage = e.getMessage();
1747                                  if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1748                                  updateStatus = "F";
1749                                  applyChangesToAppRolesRequest(app.getId(), user.getId(),
1750                                  updateStatus, epRequestId.get(0));
1751                                  }
1752                         }
1753
1754                 }
1755                 return new ExternalRequestFieldsValidator(result, reqMessage);
1756         }
1757         
1758         /**
1759          * 
1760          * @param roleInAppForUserList
1761          * @param mapper
1762          * @param applicationsRestClientService
1763          * @param appId
1764          * @param userId
1765          * @return  Set<EcompRole>
1766          * @throws JsonProcessingException
1767          * @throws HTTPException
1768          */
1769         private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1770                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1771                         throws JsonProcessingException, HTTPException {
1772                 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1773                 return updatedUserRoles;
1774         }
1775         
1776         /**
1777          * It constructs and returns list of user app roles when the external API role approval system calls
1778          * this method
1779          * 
1780          * @param roleInAppForUserList
1781          * @param appId
1782          * @return list of user app roles
1783          * @throws Exception
1784          *                 throws exceptions if role id does not exits 
1785          */
1786         private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1787                         Long appId, String appName) throws Exception {
1788                 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1789                 EPRole existingAppRole = null;
1790                 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1791                         RoleInAppForUser ecompRole = new RoleInAppForUser();
1792                         existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1793                         if (existingAppRole == null) {
1794                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1795                                                 roleInAppForUserList);
1796                                 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1797                         }
1798                         if (!existingAppRole.getActive()) {
1799                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1800                                                 roleInAppForUserList);
1801                                 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1802                         } else {
1803                                 
1804                                 List<EPRole> roleInfo = externalAccessRolesService.getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1805                                 EPRole adminRole = new EPRole();
1806                                 if(roleInfo.size()>0)
1807                                 {
1808                                         adminRole = roleInfo.get(0);
1809                                         logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getName());
1810                                 }
1811                                 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(adminRole.getName())) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1812                                 ecompRole.roleName = roleInAppForUser.getRoleName();
1813                                 ecompRole.isApplied = true;
1814                                 existingUserRoles.add(ecompRole);
1815                         }
1816                 }
1817                 return existingUserRoles;
1818         }
1819         
1820         
1821
1822         /**
1823          * 
1824          * @param userId
1825          * @param app
1826          * @param applicationsRestClientService
1827          * @return EPUser
1828          * @throws HTTPException
1829          */
1830         protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1831                         throws HTTPException {
1832                 // local app
1833                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1834                         // Map<String,String> params = new HashMap<String,String>();
1835                         // params.put("sbcid",userId);
1836                         @SuppressWarnings("unchecked")
1837                         List<EPUser> userList = (List<EPUser>) dataAccessService
1838                                         .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1839                         if (userList != null && !userList.isEmpty())
1840                                 return userList.get(0);
1841                         else
1842                                 return null;
1843                 }
1844                 // remote app
1845                 
1846                 return getUser(userId, app, applicationsRestClientService);
1847         }
1848         
1849         protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1850                         throws HTTPException {
1851                 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1852
1853         }
1854         
1855         protected boolean isAppUpgradeVersion(EPApp app){
1856                 return true;
1857         }
1858         
1859         
1860         public ExternalSystemAccess getExternalRequestAccess(){
1861                 ExternalSystemAccess res = null; 
1862                 try {
1863                         res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1864                                         Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1865                 } catch (Exception e) {
1866                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1867                 }
1868                 return res;             
1869         }
1870         
1871         /*
1872          * (non-Javadoc)
1873          * 
1874          * @see org.onap.portalapp.portal.service.UserRolesService#
1875          * getAppRolesForUser(java.lang.Long, java.lang.String)
1876          */
1877         @SuppressWarnings("unchecked")
1878         public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1879         List<RoleInAppForUser> rolesInAppForUser = null;
1880         EPApp app = appsService.getApp(appId);
1881         logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1882         try {
1883                 // for onap portal app, no need to make a remote call
1884                 List<Role> roleList = new ArrayList<>();
1885                 if (appId == PortalConstants.PORTAL_APP_ID) {           
1886                         if(app.getCentralAuth()){
1887                                 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1888                                 for(CentralV2Role cenRole : cenRoleList){
1889                                         Role role = new Role();
1890                                         role.setActive(cenRole.getActive());
1891                                         role.setId(cenRole.getId());
1892                                         role.setName(cenRole.getName());
1893                                         role.setPriority(cenRole.getPriority());
1894                                         roleList.add(role);
1895                                 }
1896                         }else{
1897                                 roleList = roleService.getAvailableRoles(userId);
1898                         }
1899                         List<Role> activeRoleList = new ArrayList<Role>();
1900                         for(Role role: roleList) {
1901                                 if(role.getActive()) {
1902                                         if(role.getId() != 1){ // prevent portal admin from being added
1903                                                 activeRoleList.add(role);
1904                                         } else if(extRequestValue){
1905                                                 activeRoleList.add(role);
1906                                         }
1907                                 }
1908                                         
1909                         }
1910                         EPUser localUser  = getUserFromApp(userId, app, applicationsRestClientService);
1911                         // If localUser does not exists return roles
1912                         Set<EPRole> roleSet = null;
1913                         EPRole[] roleSetList = null;
1914                         if(localUser != null){
1915                                 roleSet = localUser.getAppEPRoles(app);
1916                                 roleSetList = roleSet.toArray(new EPRole[0]);
1917                         }
1918                         rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1919                         return rolesInAppForUser;
1920                 }
1921                 
1922                 EcompRole[] appRoles = null;
1923                 boolean checkIfUserisApplicationAccAdmin = false;
1924                 List<EcompRole> roles = new ArrayList<>();
1925                         if (app.getCentralAuth()) {
1926                                 final Map<String, Long> appParams = new HashMap<>();
1927                                 appParams.put("appId", app.getId());
1928                                 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1929                                                 appParams, null);
1930
1931                                 EPApp application = appService.getApp(appId);
1932                                  checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1933                                                 application);
1934
1935                                 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1936                                 for (EPRole role : applicationRoles) {
1937                                         Map<String, Long> params = new HashMap<>();
1938                                         params.put("roleId", role.getId());
1939                                         params.put(APP_ID, app.getId());
1940                                         List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1941                                                         .executeNamedQuery("getAppRoleFunctionList", params, null);
1942
1943                                         // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1944                                         // new TreeSet<>();
1945                                         SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1946                                         for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1947
1948                                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1949                                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1950                                                 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1951                                                 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1952                                                 String name = roleFunc.getName();
1953
1954                                                 RoleFunction function = new RoleFunction();
1955                                                 function.setAction(action);
1956                                                 function.setType(type);
1957                                                 function.setCode(functionCode);
1958                                                 function.setName(name);
1959                                                 roleFunctionSet.add(function);
1960                                                 role.setRoleFunctions(roleFunctionSet);
1961
1962                                         }
1963                                         rolesetwithfunctioncds.add(role);
1964
1965
1966                                 }
1967
1968                                 for (EPRole role1 : rolesetwithfunctioncds) {
1969                                         EcompRole ecompRole = new EcompRole();
1970                                         ecompRole.setId(role1.getId());
1971                                         ecompRole.setName(role1.getName());
1972                                         ecompRole.setRoleFunctions(role1.getRoleFunctions());
1973                                         roles.add(ecompRole);
1974
1975                                 }
1976                                         if (checkIfUserisApplicationAccAdmin) {
1977                                         appRoles = roles.toArray(new EcompRole[roles.size()]);
1978                                         logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1979                                 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1980                                         List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1981                                         List<String> roleAdminAppRolesNames = new ArrayList<>();
1982                                         final Map<String, Long> userParams = new HashMap<>();
1983                                         userParams.put("userId", user.getId()); 
1984                                         List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1985
1986                                         List<EcompRole> userapproverRolesList = new ArrayList<>();
1987                                         for (String str : getUserApproverRoles) {
1988                                                 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1989                                                 if (epRole != null)
1990                                                         userapproverRolesList.add(epRole);
1991                                         }
1992 //                                      roles.removeAll(userapproverRolesList);
1993                                         for (EcompRole role : userapproverRolesList) {
1994
1995                                                 List<RoleFunction> roleFunList = new ArrayList<>();
1996                                                 roleFunList.addAll(role.getRoleFunctions());
1997                                                 boolean checkIfFunctionsExits = roleFunList.stream()
1998                                                                 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1999                                                 if (checkIfFunctionsExits) {
2000                                                         roleAdminAppRoles.add(role);
2001                                                         List<RoleFunction> filteredList = roleFunList.stream()
2002                                                                         .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
2003                                                         roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
2004                                                                         .collect(Collectors.toList()));
2005 //                                                      roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
2006 //                                                                      .collect(Collectors.toList());
2007                                                 }
2008                                         }
2009                                                 for (String name : roleAdminAppRolesNames) {
2010                                                         EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
2011                                                                         .orElse(null);
2012                                                         if (ecompRole != null)
2013                                                                 roleAdminAppRoles.add(ecompRole);
2014                                                 
2015                                         }
2016                                         appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
2017
2018                                 }
2019                         } else{
2020                         appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
2021                 }
2022                 // Test this error case, for generating an internal ONAP Portal
2023                 // error
2024                 // EcompRole[] appRoles = null;
2025                 // If there is an exception in the rest client api, then null will
2026                 // be returned.
2027                 if (appRoles != null) {
2028                         if(!app.getCentralAuth()) {
2029                         syncAppRoles(sessionFactory, appId, appRoles);
2030                         }
2031                         EcompRole[] userAppRoles = null;
2032                         try {
2033                                 try {
2034                                         
2035                                         if(app.getCentralAuth()){
2036                                                 final Map<String, String> params = new HashMap<>();
2037                                                 final Map<String, Long> userParams = new HashMap<>();
2038                                                 params.put("orgUserIdValue", userId);
2039                                                 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
2040                                                 userParams.put("appId", app.getId());
2041                                                 userParams.put("userId", actualUser.get(0).getId());    
2042                                                 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
2043                                                         
2044                                                 List<EcompRole> setUserRoles = new ArrayList<>();
2045                                                         for(EPUserAppCurrentRoles role : userAppsRolesList){
2046                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
2047                                                                 EcompRole ecompRole = new EcompRole();
2048                                                                 ecompRole.setId(role.getRoleId());
2049                                                                 ecompRole.setName(role.getRoleName());
2050                                                                 setUserRoles.add(ecompRole);
2051                                                         }
2052                                                 
2053                                                         boolean checkIfUserisAccAdmin = setUserRoles.stream()
2054                                                                         .anyMatch(ecompRole -> ecompRole.getId() == 999L);
2055                                                         
2056                                                 if (!checkIfUserisAccAdmin) {
2057                                                         List<EcompRole> userApplicationRolesList = setUserRoles;
2058                                                         List<EcompRole> appRolesList = Arrays.asList(appRoles);
2059                                                          Set<EcompRole> finalUserAppRolesList = new HashSet<>();
2060
2061                                                         List<String> roleNames = new ArrayList<>();
2062                                                                 for (EcompRole role : userApplicationRolesList) {
2063                                                                         EcompRole epRole = appRolesList.stream()
2064                                                                                         .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
2065                                                                         List<RoleFunction> roleFunList = new ArrayList<>();
2066                                                                         
2067                                                                         if (epRole != null) {
2068                                                                                 if (epRole.getRoleFunctions().size() > 0)
2069                                                                                         roleFunList.addAll(epRole.getRoleFunctions());
2070                                                                                 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
2071                                                                                                 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
2072                                                                                 if (checkIfFunctionsExits) {
2073                                                                                         finalUserAppRolesList.add(role);
2074                                                                                         List<RoleFunction> filteredList = roleFunList.stream()
2075                                                                                                         .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
2076                                                                                                         .collect(Collectors.toList());
2077                                                                                         roleNames = filteredList.stream().map(RoleFunction::getCode)
2078                                                                                                         .collect(Collectors.toList());
2079                                                                                 }else{
2080                                                                                         roleNames.add(epRole.getName());
2081                                                                                 }
2082                                                                         }
2083                                                                         for (String name : roleNames) {
2084                                                                                 EcompRole ecompRole = appRolesList.stream()
2085                                                                                                 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
2086                                                                                 if (ecompRole != null)
2087                                                                                         finalUserAppRolesList.add(ecompRole);
2088                                                                         }
2089                                                                 }
2090                                                                 
2091                                                                 
2092                                                         for (String name : roleNames) {
2093                                                                 
2094                                                                 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
2095                                                                                 role -> role.getRoleName().equalsIgnoreCase(name));             
2096                                                                 if(checkIfFunctionsExits)
2097                                                                 {
2098                                                                         EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
2099                                                                                         .findAny().orElse(null);
2100                                                                         if(epRole != null)
2101                                                                         setUserRoles.add(epRole);
2102                                                                 }
2103                                                                 
2104                                                         }
2105                                                         userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
2106                                                 } 
2107                                         }else{
2108                                                 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
2109                                                                 String.format("/user/%s/roles", userId));
2110                                         }
2111                                 } catch (HTTPException e) {
2112                                         // Some apps are returning 400 if user is not found.
2113                                         if (e.getResponseCode() == 400) {
2114                                                 logger.debug(EELFLoggerDelegate.debugLogger,
2115                                                                 "getAppRolesForUser caught exception with response code 400; continuing", e);
2116                                         } else {
2117                                                 // Other response code, let it come thru.
2118                                                 throw e;
2119                                         }
2120                                 }
2121                                 if (userAppRoles == null) {
2122                                         if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
2123                                                 EcompPortalUtils.setExternalAppResponseCode(200);
2124                                                 String message = String.format(
2125                                                                 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2126                                                                                 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2127                                                                                 + "Overriding to 200 until framework SDK returns a useful response.",
2128                                                                 Long.toString(appId), userId);
2129                                                 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2130                                         }
2131                                 }
2132                                 
2133                                  HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2134                                         ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2135                                         if(userAppRoles != null){
2136                                                 for (int i = 0; i < userAppRoles.length; i++) {
2137                                                         if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2138                                                                 EcompRole role = new EcompRole();
2139                                                                 role.setId(userAppRoles[i].getId());
2140                                                                 role.setName(userAppRoles[i].getName());
2141                                                                 activeRoles.add(role);
2142                                                         }
2143                                                 }
2144                                         }
2145                                         EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2146                                 
2147                                         
2148                                         boolean checkIfUserisRoleAdmin = adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin;
2149                                         
2150                                 // If the remote application isn't down we MUST sync user
2151                                 // roles here in case we have this user here!
2152                                 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null,checkIfUserisRoleAdmin,appRoles);
2153                         } catch (Exception e) {
2154                                 // TODO: we may need to check if user exists, maybe remote
2155                                 // app is down.
2156                                 String message = String.format(
2157                                                 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2158                                                 Long.toString(appId));
2159                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2160                                 userAppRoles = new EcompRole[0];
2161                         }
2162                         rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2163                 }
2164         } catch (Exception e) {
2165                 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2166                                 Long.toString(appId));
2167                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2168         }
2169         return rolesInAppForUser;
2170         }
2171         
2172         private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2173                         ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2174                         throws JsonProcessingException, HTTPException {
2175                 boolean result = false;
2176                 ObjectMapper mapper = new ObjectMapper();
2177                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2178                 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2179                 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2180                 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2181                 return result;
2182         }
2183
2184         @SuppressWarnings("unchecked")
2185         public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2186                 FieldsValidator fieldsValidator = new FieldsValidator();
2187                 final Map<String, Long> params = new HashMap<>();
2188                 List<EPUserAppRoles>  appRole= null;
2189                 try {
2190                         logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2191                         boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2192                                 userAppRolesData.getAppId(), user.getId());
2193                         logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2194                                                 
2195                         params.put("appId", userAppRolesData.getAppId());
2196                         EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2197                         epAppRolesRequestData.setCreatedDate(new Date());
2198                         epAppRolesRequestData.setUpdatedDate(new Date());
2199                         epAppRolesRequestData.setUserId(user.getId());
2200                         epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2201                         epAppRolesRequestData.setRequestStatus("P");
2202                         List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2203                         Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2204                         dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2205                         for (RoleInAppForUser userAppRoles : appRoleIdList) {
2206                                 Boolean isAppliedVal = userAppRoles.isApplied;
2207                                 params.put("appRoleId", userAppRoles.roleId);                           
2208                                 if (isAppliedVal) {
2209                                         appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2210                                         if (!appRole.isEmpty()) {
2211                                                 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2212                                                 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2213                                                 epAppRoleDetail.setReqType("P");
2214                                                 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2215                                                 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2216                                         }
2217                                 }                       
2218                         }
2219                         epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2220                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2221
2222                 } catch (Exception e) {
2223                         logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2224                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2225                 }
2226                 return fieldsValidator;
2227         }
2228
2229         public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {      
2230                 Map<String, String> params = new HashMap<>();
2231                 params.put("userid", userid.getId().toString());
2232                 //params.put("appid", appid);
2233                 params.put("appName", appName);
2234                         
2235                 @SuppressWarnings("unchecked")
2236                 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2237                                 .executeNamedQuery("userAppCatalogRoles", params, null);
2238                 return userAppRoles;    
2239         }
2240         
2241         public String updateRemoteUserProfile(String orgUserId, Long appId) {
2242                 ObjectMapper mapper = new ObjectMapper();
2243                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2244                 EPUser client = searchService.searchUserByUserId(orgUserId);
2245                 EPUser newUser = new EPUser();
2246                 newUser.setActive(client.getActive());
2247                 newUser.setFirstName(client.getFirstName());
2248                 newUser.setLastName(client.getLastName());
2249                 newUser.setLoginId(client.getLoginId());
2250                 newUser.setLoginPwd(client.getLoginPwd());
2251                 newUser.setMiddleInitial(client.getMiddleInitial());
2252                 newUser.setEmail(client.getEmail());
2253                 newUser.setOrgUserId(client.getLoginId());
2254                 try {
2255                         String userAsString = mapper.writeValueAsString(newUser);
2256                         List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2257                         // applicationsRestClientService.post(EPUser.class, appId,
2258                         // userAsString, String.format("/user", orgUserId));
2259                         for (EPApp eachApp : appList) {
2260                                 try {
2261                                         applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2262                                                         String.format("/user/%s", orgUserId));
2263                                 } catch (Exception e) {
2264                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2265                                                         + " in remote app. appId = " + eachApp.getId());
2266                                 }
2267                         }
2268                 } catch (Exception e) {
2269                         logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2270                         return "failure";
2271                 }
2272
2273                 return "success";
2274         }
2275
2276
2277         /*
2278          * (non-Javadoc)
2279          * 
2280          * @see org.onap.portalapp.portal.service.UserRolesService#
2281          * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2282          */
2283         @SuppressWarnings("deprecation")
2284         public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2285                 // Find the records for this user-app combo, if any
2286                 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2287                 @SuppressWarnings("unchecked")
2288                 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2289                 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2290                 return roleList;
2291         }
2292         
2293         /**
2294          * It retrieves and returns list of user app roles for local and remote applications based app id
2295          * 
2296          * @param appId
2297          * @return list of user app roles
2298          * @throws HTTPException 
2299          */
2300         public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2301                 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2302                 
2303                 EPApp app = appsService.getApp(appId);
2304                 //If local or centralized application
2305                 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2306                         @SuppressWarnings("unchecked")
2307                         List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2308                         for (EPUser user : userList) {
2309                                 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2310                                 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2311                                         userApplicationRoles.add(userWithAppRoles);
2312                         }
2313
2314                 } 
2315                 // remote app
2316                 else {  
2317                         RemoteUserWithRoles[] remoteUsers = null;
2318                         String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2319                         
2320                         remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2321                         
2322                         userApplicationRoles = new ArrayList<UserApplicationRoles>();
2323                         for (RemoteUserWithRoles remoteUser : remoteUsers) {
2324                                 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2325                                 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2326                                         userApplicationRoles.add(userWithRemoteAppRoles);
2327                                 } else {
2328                                         logger.debug(EELFLoggerDelegate.debugLogger,
2329                                                         "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2330                                 }
2331                         }
2332                 }
2333                 
2334                 return userApplicationRoles;
2335         }
2336         
2337         /**
2338          * 
2339          * @param appId
2340          * @param user
2341          * @param appgetUsersFromAppEndpoint
2342          * @return
2343          */
2344         private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2345                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2346                 userWithRemoteAppRoles.setAppId(appId);
2347                 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2348                 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2349                 userWithRemoteAppRoles.setLastName(user.getLastName());
2350                 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2351                 return userWithRemoteAppRoles;
2352         }
2353
2354         /**
2355          * 
2356          * @param user
2357          * @param app
2358          * @return
2359          */
2360         @SuppressWarnings("unchecked")
2361         private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2362                 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2363                 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2364                 for (EPRole role : roleSet) {
2365                         logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2366                         RemoteRole rRole = new RemoteRole();
2367                         rRole.setId(role.getId());
2368                         rRole.setName(role.getName());
2369                         roleList.add(rRole);
2370                 }
2371                 
2372                 //Get the active roles of user for that application using query
2373                 List<EPRole> userEpRoleList = new ArrayList<>();
2374                 final Map<String, Long> params = new HashMap<>();
2375                 params.put("appId", app.getId());
2376                 params.put("userId", user.getId());
2377                 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2378
2379                 for (EPRole remoteUserRoleList : userEpRoleList) {
2380
2381                         RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2382                                         .findAny().orElse(null);
2383                         if (remoteRoleListId == null) {
2384                                 logger.debug(EELFLoggerDelegate.debugLogger,
2385                                                 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2386
2387                                                 remoteUserRoleList.getName());
2388                                 RemoteRole role = new RemoteRole();
2389                                 role.setId(remoteUserRoleList.getId());
2390                                 role.setName(remoteUserRoleList.getName());
2391
2392                                 roleList.add(role);
2393                         }
2394
2395                 }
2396
2397                 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2398
2399                 return roleList;
2400                 
2401                 
2402                 
2403         }
2404
2405         public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2406
2407                 ObjectMapper mapper = new ObjectMapper();
2408                 try {
2409                         return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2410                 } catch (IOException e) {
2411                         logger.error(EELFLoggerDelegate.errorLogger,
2412                                         "doGetUsers : Failed : Unexpected property in incoming JSON",
2413                                         e);
2414                         logger.error(EELFLoggerDelegate.errorLogger,
2415                                         "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2416                 }
2417
2418                 return new RemoteUserWithRoles[0];
2419         }
2420
2421         @SuppressWarnings("unchecked")
2422         public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2423                 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2424                 final Map<String, Long> params = new HashMap<>();
2425                 params.put("appId", appId);
2426                 params.put("userId", userId);
2427                 params.put("roleId", roleId);
2428                 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2429                 return userRoleList;
2430         }
2431         
2432         
2433         /*public static void main(String[] args) {
2434                 List<EcompRole> str1 = new ArrayList<String>();
2435                 str1.add("A");
2436                 str1.add("B");
2437                 str1.add("C");
2438                 str1.add("D");
2439
2440                 List<String> str2 = new ArrayList<String>();
2441                 str2.add("D");
2442                 str2.add("E");
2443
2444                 List<EcompRole> userApplicationRolesList = setUserRoles;
2445                 List<EcompRole> appRolesList = Arrays.asList(appRoles);
2446                 
2447         }*/
2448 }