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