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