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