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