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