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