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