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