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