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