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