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