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