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