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