Junit for Duplicate Record Exception
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / UserRolesController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  *
37  */
38 package org.onap.portalapp.portal.controller;
39
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collections;
43 import java.util.Comparator;
44 import java.util.List;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import org.apache.cxf.transport.http.HTTPException;
48 import org.onap.portalapp.controller.EPRestrictedBaseController;
49 import org.onap.portalapp.portal.domain.EPApp;
50 import org.onap.portalapp.portal.domain.EPRole;
51 import org.onap.portalapp.portal.domain.EPUser;
52 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
53 import org.onap.portalapp.portal.domain.EcompAuditLog;
54 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
55 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
56 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
57 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
58 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
59 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
60 import org.onap.portalapp.portal.service.AdminRolesService;
61 import org.onap.portalapp.portal.service.ApplicationsRestClientService;
62 import org.onap.portalapp.portal.service.EPAppService;
63 import org.onap.portalapp.portal.service.SearchService;
64 import org.onap.portalapp.portal.service.UserRolesService;
65 import org.onap.portalapp.portal.transport.AppNameIdIsAdmin;
66 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
67 import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
68 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
69 import org.onap.portalapp.portal.transport.FieldsValidator;
70 import org.onap.portalapp.portal.transport.RoleInAppForUser;
71 import org.onap.portalapp.portal.transport.UserApplicationRoles;
72 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
73 import org.onap.portalapp.portal.utils.EcompPortalUtils;
74 import org.onap.portalapp.portal.utils.PortalConstants;
75 import org.onap.portalapp.util.EPUserUtils;
76 import org.onap.portalsdk.core.domain.AuditLog;
77 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
78 import org.onap.portalsdk.core.restful.domain.EcompRole;
79 import org.onap.portalsdk.core.service.AuditService;
80 import org.onap.portalsdk.core.service.DataAccessService;
81 import org.onap.portalsdk.core.util.SystemProperties;
82 import org.slf4j.MDC;
83 import org.springframework.beans.factory.annotation.Autowired;
84 import org.springframework.context.annotation.EnableAspectJAutoProxy;
85 import org.springframework.web.bind.annotation.PathVariable;
86 import org.springframework.web.bind.annotation.RequestBody;
87 import org.springframework.web.bind.annotation.RequestMapping;
88 import org.springframework.web.bind.annotation.RequestMethod;
89 import org.springframework.web.bind.annotation.RequestParam;
90 import org.springframework.web.bind.annotation.RestController;
91
92 @RestController
93 @org.springframework.context.annotation.Configuration
94 @EnableAspectJAutoProxy
95 @EPAuditLog
96 public class UserRolesController extends EPRestrictedBaseController {
97
98     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
99
100     @Autowired
101     private SearchService searchService;
102     @Autowired
103     private AdminRolesService adminRolesService;
104     private @Autowired UserRolesService userRolesService;
105     @Autowired
106     private ApplicationsRestClientService applicationsRestClientService;
107     @Autowired
108     private AuditService auditService;
109     @Autowired
110         private DataAccessService dataAccessService;
111
112     private static final String FAILURE = "failure";
113
114     /**
115      * RESTful service method to fetch users in the WebPhone external service
116      *
117      * @param request HttpServletRequest
118      * @param searchString search string
119      * @param response HttpServletResponse
120      * @return array of found users as json
121      */
122     @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
123     public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString,
124             HttpServletResponse response) {
125         EPUser user = EPUserUtils.getUserSession(request);
126         String searchResult = null;
127         if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)
128                 && !adminRolesService.isRoleAdmin(user)) {
129             EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
130         } else {
131             searchString = searchString.trim();
132             if (searchString.length() > 2) {
133                 searchResult = searchService.searchUsersInPhoneBook(searchString);
134             } else {
135                 logger.info(EELFLoggerDelegate.errorLogger,
136                         "getPhoneBookSearchResult - too short search string: " + searchString);
137             }
138         }
139         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
140
141         return searchResult;
142     }
143
144     /**
145      * RESTful service method to fetch applications where user is admin
146      *
147      * @param request HttpServletRequest
148      * @param orgUserId search string
149      * @param response HttpServletResponse
150      * @return for GET: array of all applications with boolean isAdmin=true/false for each application
151      */
152     @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
153             RequestMethod.GET }, produces = "application/json")
154     public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request,
155             @RequestParam("user") String orgUserId, HttpServletResponse response) {
156
157         EPUser user = EPUserUtils.getUserSession(request);
158         AppsListWithAdminRole result = null;
159         if (!adminRolesService.isSuperAdmin(user)) {
160             EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
161         } else {
162             if (EcompPortalUtils.legitimateUserId(orgUserId)) {
163                 result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
164             } else {
165                 logger.info(EELFLoggerDelegate.errorLogger,
166                         "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
167                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
168             }
169         }
170
171         StringBuilder adminAppRoles = new StringBuilder();
172         if (result != null) {
173             if (!result.appsRoles.isEmpty()) {
174                 adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
175                 for (AppNameIdIsAdmin adminAppRole : result.appsRoles) {
176                     if (adminAppRole.isAdmin) {
177                         adminAppRoles.append(adminAppRole.appName + ", ");
178                     }
179                 }
180                 adminAppRoles.append("}.");
181             } else {
182                 adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
183             }
184         } else {
185             logger.error(EELFLoggerDelegate.errorLogger,
186                     "putAppWithUserRoleStateForUser: getAppsWithAdminRoleStateForUser result is null");
187         }
188
189         logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
190
191         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
192
193         return result;
194     }
195
196     /**
197      *
198      * @param request HttpServletRequest
199      * @param newAppsListWithAdminRoles new apps
200      * @param response HttpServletResponse
201      * @return FieldsValidator
202      */
203     @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
204             RequestMethod.PUT }, produces = "application/json")
205     public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request,
206             @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
207
208         // newAppsListWithAdminRoles.appsRoles
209         FieldsValidator fieldsValidator = new FieldsValidator();
210         StringBuilder newAppRoles = new StringBuilder();
211         if (newAppsListWithAdminRoles != null) {
212             if (!newAppsListWithAdminRoles.appsRoles.isEmpty()) {
213                 newAppRoles
214                         .append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { ");
215                 for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
216                     if (adminAppRole.isAdmin) {
217                         newAppRoles.append(adminAppRole.appName + " ,");
218                     }
219                 }
220                 newAppRoles.deleteCharAt(newAppRoles.length() - 1);
221                 newAppRoles.append("}.");
222             } else {
223                 newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
224             }
225         } else {
226             logger.error(EELFLoggerDelegate.errorLogger,
227                     "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null");
228             fieldsValidator.httpStatusCode = (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
229         }
230
231         logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
232
233         EPUser user = EPUserUtils.getUserSession(request);
234         boolean changesApplied = false;
235
236         if (!adminRolesService.isSuperAdmin(user)) {
237             EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
238         } else {
239             changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
240             AuditLog auditLog = new AuditLog();
241             auditLog.setUserId(user.getId());
242             auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
243             if (newAppsListWithAdminRoles != null) {
244                 auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId);
245             }
246             auditLog.setComments(
247                     EcompPortalUtils.truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE));
248             auditService.logActivity(auditLog, null);
249
250             MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
251             MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
252             EcompPortalUtils.calculateDateTimeDifferenceForLog(
253                     MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
254                     MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
255             if (newAppsListWithAdminRoles != null) {
256                 logger.info(EELFLoggerDelegate.auditLogger,
257                         EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
258                                 EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
259                                 newAppsListWithAdminRoles.orgUserId, newAppRoles.toString()));
260             }
261             MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
262             MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
263             MDC.remove(SystemProperties.MDC_TIMER);
264         }
265         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
266
267         return fieldsValidator;
268     }
269
270     /**
271      * It returns a list of user app roles for single app
272      *
273      * @param request HttpServletRequest
274      * @param response HttpServletResponse
275      * @param orgUserId user ID
276      * @param appid application ID
277      * @param extRequestValue set to false if request is from users page otherwise true
278      * @return List<RoleInAppForUser>
279      */
280     @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
281             RequestMethod.GET }, produces = "application/json")
282     public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
283             @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
284             @RequestParam("isSystemUser") Boolean isSystemUser,
285             HttpServletResponse response) {
286         EPUser user = EPUserUtils.getUserSession(request);
287         List<RoleInAppForUser> result = null;
288         String feErrorString = "";
289         if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) {
290             logger.debug(EELFLoggerDelegate.debugLogger,
291                     "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}",
292                     adminRolesService.isAccountAdmin(user), adminRolesService.isRoleAdmin(user));
293             EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
294             feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
295         } else {
296                 try {
297                         if(orgUserId!=null) {
298                                 EPUser localUser  = getUserInfo(orgUserId,applicationsRestClientService);
299                                 if(localUser !=null) {
300                                         if(localUser.isSystemUser()) {
301                                                 isSystemUser = true;
302                                         }
303                                 }
304                         }
305                         } catch (Exception e) {
306                                 logger.error(EELFLoggerDelegate.errorLogger, "isSystemUser update failed", e);
307                         }
308             if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) {
309                 result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user);
310                 logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", result, appid);
311                 int responseCode = EcompPortalUtils.getExternalAppResponseCode();
312                 if (responseCode != 0 && responseCode != 200) {
313                     // external error
314                     response.setStatus(responseCode);
315                     feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
316                 } else if (result == null) {
317                     // If the result is null, there was an internal onap error
318                     // in the service call.
319                     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
320                     feErrorString = EcompPortalUtils.getFEErrorString(true,
321                             HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
322                 }
323             } else {
324                 logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
325                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
326                 feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
327             }
328         }
329
330         StringBuilder sbUserApps = new StringBuilder();
331         if (result != null && !result.isEmpty()) {
332             sbUserApps.append("User '" + orgUserId + "' has Roles={");
333             for (RoleInAppForUser appRole : result) {
334                 if (appRole.isApplied) {
335                     sbUserApps.append(appRole.roleName + ", ");
336                 }
337             }
338             sbUserApps.append("} assigned to the appId '" + appid + "'.");
339         } else {
340             // Not sure creating an empty object will make any difference
341             // but would like to give it a shot for defect #DE221057
342             if (result == null) {
343                 result = new ArrayList<>();
344             }
345             sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
346         }
347         logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
348
349         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
350         if (feErrorString != "") {
351             logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
352
353             response.addHeader("FEErrorString", feErrorString);
354             response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
355         }
356         return result;
357     }
358
359     @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
360             RequestMethod.PUT }, produces = "application/json")
361     public PortalRestResponse<String> putAppWithUserRoleStateForUser(HttpServletRequest request,
362             @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
363         // FieldsValidator fieldsValidator = new FieldsValidator();
364         PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
365         StringBuilder sbUserApps = new StringBuilder();
366         if (newAppRolesForUser != null) {
367             sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId());
368             if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) {
369                 sbUserApps.append("' has roles = { ");
370                 for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) {
371                     if (appRole.isApplied) {
372                         sbUserApps.append(appRole.roleName + " ,");
373                     }
374                 }
375                 sbUserApps.deleteCharAt(sbUserApps.length() - 1);
376                 sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId());
377             } else {
378                 sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId());
379             }
380         }
381         logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString());
382
383         EPUser user = EPUserUtils.getUserSession(request);
384         // boolean changesApplied = false;
385         ExternalRequestFieldsValidator changesApplied = null;
386
387         if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) {
388             EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
389         } else if (newAppRolesForUser == null) {
390             logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: newAppRolesForUser is null");
391         } else {
392             changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
393             try {
394                 if (changesApplied.isResult()) {
395                     logger.info(EELFLoggerDelegate.applicationLogger,
396                             "putAppWithUserRoleStateForUser: succeeded for app {}, user {}",
397                             newAppRolesForUser.getAppId(),
398                             newAppRolesForUser.getAppId());
399
400                     MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
401                             EPEELFLoggerAdvice.getCurrentDateTimeUTC());
402                     AuditLog auditLog = new AuditLog();
403                     auditLog.setUserId(user.getId());
404                     auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
405                     auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId());
406                     auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(),
407                             PortalConstants.AUDIT_LOG_COMMENT_SIZE));
408                     auditService.logActivity(auditLog, null);
409
410                     MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
411                             EPEELFLoggerAdvice.getCurrentDateTimeUTC());
412                     EcompPortalUtils.calculateDateTimeDifferenceForLog(
413                             MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
414                             MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
415                     logger.info(EELFLoggerDelegate.auditLogger,
416                             EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
417                                     EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
418                                     newAppRolesForUser.getOrgUserId(), sbUserApps.toString()));
419                     MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
420                     MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
421                     MDC.remove(SystemProperties.MDC_TIMER);
422                     portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
423
424                 }
425                 if (!changesApplied.isResult())
426                     throw new Exception(changesApplied.getDetailMessage());
427
428             } catch (Exception e) {
429                 logger.error(EELFLoggerDelegate.errorLogger,
430                         "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.getAppId(),
431                         newAppRolesForUser.getOrgUserId(), e);
432                 portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
433             }
434         }
435
436         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
437         return portalResponse;
438     }
439
440     @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = {
441             RequestMethod.GET }, produces = "application/json")
442     public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,
443             HttpServletResponse response) {
444
445         String updateRemoteUserFlag = FAILURE;
446         try {
447             // saveNewUser = userService.saveNewUser(newUser);
448             String orgUserId = request.getParameter("loginId");
449             Long appId = Long.parseLong(request.getParameter("appId"));
450             userRolesService.updateRemoteUserProfile(orgUserId, appId);
451
452         } catch (Exception e) {
453             logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
454             return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
455         }
456         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
457
458     }
459
460     @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = {
461             RequestMethod.GET }, produces = "application/json")
462     public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request,
463             @PathVariable("appId") Long appId) throws HTTPException {
464         try {
465             logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
466             return userRolesService.getUsersFromAppEndpoint(appId);
467         } catch (Exception e) {
468             logger.error(EELFLoggerDelegate.errorLogger, "getUsersFromAppEndpoint failed", e);
469             return new ArrayList<>();
470         }
471     }
472
473     @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = {
474             RequestMethod.GET }, produces = "application/json")
475     public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
476             throws HTTPException {
477         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
478         List<EcompRole> rolesList = Arrays.asList(appRoles);
479         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
480                 rolesList);
481
482         return rolesList;
483     }
484
485     @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = {
486             RequestMethod.GET }, produces = "application/json")
487     public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId)
488             throws HTTPException {
489         List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
490         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
491                 "response for appId=" + appId, rolesList);
492
493         return rolesList;
494     }
495
496     @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = {
497             RequestMethod.GET }, produces = "application/json")
498     public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId,
499             @PathVariable("orgUserId") String orgUserId) throws Exception {
500         if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
501             String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
502             logger.error(EELFLoggerDelegate.errorLogger, msg);
503             throw new Exception(msg);
504         }
505         EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
506                 String.format("/user/%s/roles", orgUserId));
507         if (roles.length != 1) {
508             String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
509             logger.error(EELFLoggerDelegate.errorLogger, msg);
510             throw new Exception(msg);
511         }
512
513         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
514                 "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
515         return roles[0];
516     }
517
518     @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = {
519             RequestMethod.PUT }, produces = "application/json")
520     public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request,
521             @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
522         FieldsValidator fieldsValidator = null;
523         try {
524
525             EPUser user = EPUserUtils.getUserSession(request);
526             fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user);
527             response.setStatus(fieldsValidator.httpStatusCode.intValue());
528
529         } catch (Exception e) {
530             logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
531
532         }
533         // return fieldsValidator;
534         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
535                 response.getStatus());
536         return fieldsValidator;
537     }
538
539     @RequestMapping(value = { "/portalApi/appCatalogRoles" }, method = {
540             RequestMethod.GET }, produces = "application/json")
541     public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request,
542             @RequestParam("appName") String appName) {
543         EPUser user = EPUserUtils.getUserSession(request);
544         List<EPUserAppCatalogRoles> userAppRoleList = null;
545         try {
546             userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName);
547         } catch (Exception e) {
548             logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
549
550         }
551         Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator);
552         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
553
554         return userAppRoleList;
555
556     }
557
558     private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator =
559             new Comparator<EPUserAppCatalogRoles>() {
560                 public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) {
561                     return o1.getRolename().compareTo(o2.getRolename());
562                 }
563             };
564
565     @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET,
566             produces = "application/json")
567     public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) {
568         ExternalSystemAccess result = null;
569         try {
570             result = userRolesService.getExternalRequestAccess();
571             EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
572                     result);
573         } catch (Exception e) {
574             logger.error(EELFLoggerDelegate.errorLogger, "readExternalRequestAccess failed: " + e.getMessage());
575         }
576         return result;
577     }
578
579     @RequestMapping(value = { "/portalApi/checkIfUserIsSuperAdmin" }, method = RequestMethod.GET,
580             produces = "application/json")
581     public boolean checkIfUserIsSuperAdmin(HttpServletRequest request,
582             HttpServletResponse response) {
583         EPUser user = EPUserUtils.getUserSession(request);
584         boolean isSuperAdmin = false;
585         try {
586             isSuperAdmin = adminRolesService.isSuperAdmin(user);
587         } catch (Exception e) {
588             logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage());
589         }
590         return isSuperAdmin;
591     }
592     
593     /**
594          * 
595          * @param userId
596          * @param app
597          * @param applicationsRestClientService
598          * @return EPUser
599          * @throws HTTPException
600          */
601         protected EPUser getUserInfo(String userId, ApplicationsRestClientService applicationsRestClientService)
602                         throws HTTPException {
603                 @SuppressWarnings("unchecked")
604                 List<EPUser> userList = (List<EPUser>) dataAccessService
605                                 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
606                 if (userList != null && !userList.isEmpty())
607                         return userList.get(0);
608                 else
609                         return null;
610         }
611 }