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