removed code smells
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / FunctionalMenuController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *  Modification Copyright © 2020 IBM.
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40 package org.onap.portalapp.portal.controller;
41
42 import java.io.IOException;
43 import java.text.SimpleDateFormat;
44 import java.util.ArrayList;
45 import java.util.Collections;
46 import java.util.Comparator;
47 import java.util.Date;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51
52 import javax.servlet.http.HttpServletRequest;
53 import javax.servlet.http.HttpServletResponse;
54 import javax.ws.rs.core.Response;
55
56 import org.json.JSONObject;
57 import org.onap.portalapp.controller.EPRestrictedBaseController;
58 import org.onap.portalapp.portal.domain.EPUser;
59 import org.onap.portalapp.portal.domain.SharedContext;
60 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
61 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
62 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
63 import org.onap.portalapp.portal.service.AdminRolesService;
64 import org.onap.portalapp.portal.service.FunctionalMenuService;
65 import org.onap.portalapp.portal.service.SearchService;
66 import org.onap.portalapp.portal.service.SharedContextService;
67 import org.onap.portalapp.portal.transport.BusinessCardApplicationRole;
68 import org.onap.portalapp.portal.transport.BusinessCardApplicationRolesList;
69 import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItem;
70 import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
71 import org.onap.portalapp.portal.transport.FieldsValidator;
72 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
73 import org.onap.portalapp.portal.transport.FunctionalMenuItemWithRoles;
74 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
75 import org.onap.portalapp.portal.utils.EcompPortalUtils;
76 import org.onap.portalapp.util.EPUserUtils;
77 import org.onap.portalapp.validation.DataValidator;
78 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
79 import org.onap.portalsdk.core.util.SystemProperties;
80 import org.onap.portalsdk.core.web.support.UserUtils;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.context.annotation.Configuration;
83 import org.springframework.context.annotation.EnableAspectJAutoProxy;
84 import org.springframework.web.bind.annotation.PathVariable;
85 import org.springframework.web.bind.annotation.RequestBody;
86 import org.springframework.web.bind.annotation.RequestMapping;
87 import org.springframework.web.bind.annotation.GetMapping;
88 import org.springframework.web.bind.annotation.PostMapping;
89 import org.springframework.web.bind.annotation.PutMapping;
90 import org.springframework.web.bind.annotation.DeleteMapping;
91 import org.springframework.web.bind.annotation.RequestMethod;
92 import org.springframework.web.bind.annotation.RequestParam;
93 import org.springframework.web.bind.annotation.RestController;
94
95 /**
96  * Supports menus at the top of the Portal app landing page.
97  */
98 @RestController
99 @Configuration
100 @EnableAspectJAutoProxy
101 @EPAuditLog
102 public class FunctionalMenuController extends EPRestrictedBaseController {
103
104         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuController.class);
105         private final DataValidator dataValidator = new DataValidator();
106
107         @Autowired
108         private AdminRolesService adminRolesService;
109         @Autowired
110         private FunctionalMenuService functionalMenuService;
111         @Autowired
112         private SharedContextService sharedContextService;
113         @Autowired
114         private SearchService searchService;
115
116         /**
117          * RESTful service method to fetch all the FunctionalMenuItems.
118          *
119          * @param request
120          *            HttpServletRequest
121          * @param response
122          *            HttpServletResponse
123          * @return List of FunctionalMenuItem objects
124          */
125         @GetMapping(value = { "/portalApi/functionalMenu" }, produces = "application/json")
126         public List<FunctionalMenuItem> getMenuItems(HttpServletRequest request, HttpServletResponse response) {
127                 // TODO: should only the superuser be allowed to use this API?
128                 List<FunctionalMenuItem> menuItems = null;
129                 try {
130                         menuItems = functionalMenuService.getFunctionalMenuItems();
131                         functionalMenuService.assignHelpURLs(menuItems);
132                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenu", "result =", menuItems);
133                 } catch (Exception e) {
134                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuItems failed", e);
135                 }
136                 return menuItems;
137         }
138
139         /**
140          * RESTful service method to get ONAP Portal Title.
141          *
142          * @param request
143          *            HttpServletRequest
144          * @param response
145          *            HttpServletResponse
146          * @return PortalRestResponse of ONAP portal title
147          */
148         @GetMapping(value = { "/portalApi/ecompTitle" }, produces = "application/json")
149         public PortalRestResponse<String> getECOMPTitle(HttpServletRequest request, HttpServletResponse response) {
150                 PortalRestResponse<String> portalRestResponse = null;
151                 try {
152                         String ecompTitle = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME);
153                         portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", ecompTitle);
154                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/ecompTitle", "result =", ecompTitle);
155                 } catch (Exception e) {
156                         portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
157                         logger.error(EELFLoggerDelegate.errorLogger, "getEcompTitle failed", e);
158                 }
159                 return portalRestResponse;
160         }
161
162         /**
163          * RESTful service method to fetch all the FunctionalMenuItems, both active and
164          * inactive, for the EditFunctionalMenu feature. Can only be accessed by the
165          * portal admin.
166          *
167          * @param request
168          *            HttpServletRequest
169          * @param response
170          *            HttpServletResponse
171          * @return List of FunctionalMenuItem objects
172          */
173         @GetMapping(value = {
174                         "/portalApi/functionalMenuForEditing" }, produces = "application/json")
175         public List<FunctionalMenuItem> getMenuItemsForEditing(HttpServletRequest request, HttpServletResponse response) {
176                 // TODO: should only the superuser be allowed to use this API?
177                 EPUser user = EPUserUtils.getUserSession(request);
178                 List<FunctionalMenuItem> menuItems = null;
179                 try {
180                         if (!adminRolesService.isSuperAdmin(user)) {
181                                 EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
182                         } else {
183                                 menuItems = functionalMenuService.getFunctionalMenuItems(true);
184                         }
185                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForEditing", "result =",
186                                         menuItems);
187                 } catch (Exception e) {
188                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuItemsForEditing failed", e);
189                 }
190                 return menuItems;
191         }
192
193         /**
194          * RESTful service method to fetch all the FunctionalMenuItems, active , for the
195          * Functional menu in notification Tree feature.
196          *
197          * @param request
198          *            HttpServletRequest
199          * @param response
200          *            HttpServletResponse
201          * @return List of FunctionalMenuItem objects
202          */
203         @GetMapping(value = {
204                         "/portalApi/functionalMenuForNotificationTree" }, produces = "application/json")
205         public List<FunctionalMenuItem> getMenuItemsForNotifications(HttpServletRequest request,
206                         HttpServletResponse response) {
207                 // TODO: should only the superuser be allowed to use this API?
208                 // EPUser user = EPUserUtils.getUserSession(request);
209                 List<FunctionalMenuItem> menuItems = null;
210                 try {
211                         menuItems = functionalMenuService.getFunctionalMenuItemsForNotificationTree(true);
212                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForNotificationTree", "result =",
213                                         menuItems);
214                 } catch (Exception e) {
215                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuItemsForNotifications failed", e);
216                 }
217                 return menuItems;
218         }
219
220         /**
221          * RESTful service method to fetch all FunctionalMenuItems associated with an
222          * application.
223          *
224          * @param request
225          *            HttpServletRequest
226          * @param appId
227          *            application ID
228          * @return List of FunctionalMenuItem objects
229          */
230         @GetMapping(value = {
231                         "/portalApi/functionalMenuForApp/{appId}" }, produces = "application/json")
232         public List<FunctionalMenuItem> getMenuItemsForApp(HttpServletRequest request,
233                         @PathVariable("appId") Integer appId) {
234                 // TODO: should only the superuser be allowed to use this API?
235                 List<FunctionalMenuItem> menuItems = null;
236                 try {
237                         menuItems = functionalMenuService.getFunctionalMenuItemsForApp(appId);
238                         functionalMenuService.assignHelpURLs(menuItems);
239                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForApp/" + appId, "result =",
240                                         menuItems);
241                 } catch (Exception e) {
242                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuItemsForApp failed", e);
243                 }
244                 return menuItems;
245         }
246
247         /**
248          * RESTful service method to fetch all FunctionalMenuItems associated with the
249          * applications and roles that a user has access to.
250          *
251          * @param request
252          *            HttpServletRequest
253          * @param orgUserId
254          *            user ID
255          * @return List of FunctionalMenuItem objects
256          */
257         @GetMapping(value = {
258                         "/portalApi/functionalMenuForUser/{orgUserId}" }, produces = "application/json")
259         public List<FunctionalMenuItem> getMenuItemsForUser(HttpServletRequest request,
260                         @PathVariable("orgUserId") String orgUserId) {
261                 // TODO: should only the superuser be allowed to use this API?
262                 List<FunctionalMenuItem> menuItems = null;
263                 try {
264                         menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
265                         functionalMenuService.assignHelpURLs(menuItems);
266                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId, "result =",
267                                         menuItems);
268                 } catch (Exception e) {
269                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuItemsForUser failed", e);
270                 }
271
272                 return menuItems;
273         }
274
275         /**
276          * RESTful service method to fetch all FunctionalMenuItems associated with the
277          * applications and roles that the authenticated user has access to.
278          *
279          * @param request
280          *            HttpServletRequest
281          * @param response
282          *            HttpServletResponse
283          * @return List of FunctionalMenuItem objects
284          */
285         @GetMapping(value = {
286                         "/portalApi/functionalMenuForAuthUser" }, produces = "application/json")
287         public List<FunctionalMenuItem> getMenuItemsForAuthUser(HttpServletRequest request, HttpServletResponse response) {
288
289                 EPUser user = EPUserUtils.getUserSession(request);
290                 List<FunctionalMenuItem> menuItems = null;
291                 try {
292                         if (user == null) {
293                                 EcompPortalUtils.setBadPermissions(user, response, "getMenuItemsForAuthUser");
294                         } else if (adminRolesService.isSuperAdmin(user)) {
295                                 menuItems = functionalMenuService.getFunctionalMenuItems();
296                         } else {
297                                 // calculate the menu items
298                                 String orgUserId = user.getOrgUserId();
299                                 menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
300                                 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId,
301                                                 "result =", menuItems);
302                         }
303                         functionalMenuService.assignHelpURLs(menuItems);
304                 } catch (Exception e) {
305                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuItemsForAuthUser failed", e);
306                 }
307                 return menuItems;
308         }
309
310         /**
311          * RESTful service method to fetch the details for a functional menu item.
312          * Requirement: you must be the ONAP portal super admin user.
313          *
314          * @param request
315          *            HttpServletRequest
316          * @param response
317          *            HttpServletResponse
318          * @param menuId
319          *            menu ID
320          * @return FunctionalMenuItem object
321          */
322         @GetMapping(value = {
323                         "/portalApi/functionalMenuItemDetails/{menuId}" }, produces = "application/json")
324         public FunctionalMenuItem getFunctionalMenuItemDetails(HttpServletRequest request,
325                         @PathVariable("menuId") Long menuId, HttpServletResponse response) {
326                 // TODO: return FunctionalMenuItemJson
327                 // TODO: modify FunctionalMenuItem to not include the transient fields
328                 FunctionalMenuItem menuItem = null;
329                 try {
330                         EPUser user = EPUserUtils.getUserSession(request);
331                         if (!adminRolesService.isSuperAdmin(user)) {
332                                 EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
333                         } else {
334                                 menuItem = functionalMenuService.getFunctionalMenuItemDetails(menuId);
335                                 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItemDetails/" + menuId,
336                                                 "result =", menuItem);
337                         }
338                 } catch (Exception e) {
339                         logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemDetails failed", e);
340                 }
341
342                 return menuItem;
343         }
344
345         /**
346          * RESTful service method to create a new menu item.
347          *
348          * Requirement: you must be the ONAP portal super admin user.
349          *
350          * @param request
351          *            HttpServletRequest
352          * @param response
353          *            HttpServletResponse
354          * @param menuItemJson
355          *            FunctionalMenuItemWithRoles
356          * @return FieldsValidator
357          */
358         @PostMapping(value = { "/portalApi/functionalMenuItem" })
359         public FieldsValidator createFunctionalMenuItem(HttpServletRequest request,
360                         @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) {
361                 EPUser user = EPUserUtils.getUserSession(request);
362                 FieldsValidator fieldsValidator = null;
363
364                 if(!dataValidator.isValid(menuItemJson)){
365                         fieldsValidator = new FieldsValidator();
366                         logger.warn(EELFLoggerDelegate.debugLogger,"FunctionalMenuController.createFunctionalMenuItem not valid object");
367                         fieldsValidator.httpStatusCode = (long)HttpServletResponse.SC_NOT_ACCEPTABLE;
368                         return fieldsValidator;
369                 }
370
371                 if (!adminRolesService.isSuperAdmin(user)) {
372                         logger.debug(EELFLoggerDelegate.debugLogger,
373                                         "FunctionalMenuController.createFunctionalMenuItem bad permissions");
374                         EcompPortalUtils.setBadPermissions(user, response, "createFunctionalMenuItem");
375                 } else {
376                         fieldsValidator = functionalMenuService.createFunctionalMenuItem(menuItemJson);
377                         response.setStatus(fieldsValidator.httpStatusCode.intValue());
378                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "POST result =",
379                                         response.getStatus());
380                 }
381
382                 return fieldsValidator;
383         }
384
385         /**
386          * RESTful service method to update an existing menu item
387          *
388          * Requirement: you must be the ONAP portal super admin user.
389          *
390          * @param request
391          *            HttpServletRequest
392          * @param response
393          *            HttpServletResponse
394          * @param menuItemJson
395          *            FunctionalMenuItemWithRoles
396          * @return FieldsValidator
397          */
398         @PutMapping(value = { "/portalApi/functionalMenuItem" })
399         public FieldsValidator editFunctionalMenuItem(HttpServletRequest request,
400                         @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) {
401                 EPUser user = EPUserUtils.getUserSession(request);
402                 FieldsValidator fieldsValidator = null;
403
404            if(!dataValidator.isValid(menuItemJson)){
405                            fieldsValidator = new FieldsValidator();
406                            logger.warn(EELFLoggerDelegate.debugLogger,"FunctionalMenuController.createFunctionalMenuItem not valid object");
407                            fieldsValidator.httpStatusCode = (long)HttpServletResponse.SC_NOT_ACCEPTABLE;
408                            return fieldsValidator;
409            }
410
411                 if (!adminRolesService.isSuperAdmin(user)) {
412                         EcompPortalUtils.setBadPermissions(user, response, "editFunctionalMenuItem");
413                 } else {
414                         fieldsValidator = functionalMenuService.editFunctionalMenuItem(menuItemJson);
415                         response.setStatus(fieldsValidator.httpStatusCode.intValue());
416                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "PUT result =",
417                                         response.getStatus());
418                 }
419
420                 return fieldsValidator;
421         }
422
423         /**
424          * RESTful service method to delete a menu item
425          *
426          * @param request
427          *            HttpServletRequest
428          * @param response
429          *            HttpServletResponse
430          * @param menuId
431          *            menu identifier
432          * @return FieldsValidator
433          */
434         @DeleteMapping(value = { "/portalApi/functionalMenuItem/{menuId}" })
435         public FieldsValidator deleteFunctionalMenuItem(HttpServletRequest request, @PathVariable("menuId") Long menuId,
436                         HttpServletResponse response) {
437                 EPUser user = EPUserUtils.getUserSession(request);
438                 FieldsValidator fieldsValidator = null;
439                 if (!adminRolesService.isSuperAdmin(user)) {
440                         EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
441                 } else {
442                         fieldsValidator = functionalMenuService.deleteFunctionalMenuItem(menuId);
443                         response.setStatus(fieldsValidator.httpStatusCode.intValue());
444                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "DELETE result =",
445                                         response.getStatus());
446                 }
447
448                 return fieldsValidator;
449         }
450
451         /**
452          * RESTful service to regenerate table
453          *
454          * @param request
455          *            HttpServletRequest
456          * @param response
457          *            HttpServletResponse
458          * @return FieldsValidator
459          */
460         @GetMapping(value = { "/portalApi/regenerateFunctionalMenuAncestors" })
461         public FieldsValidator regenerateAncestorTable(HttpServletRequest request, HttpServletResponse response) {
462                 // TODO: should only the superuser be allowed to use this API?
463                 EPUser user = EPUserUtils.getUserSession(request);
464                 FieldsValidator fieldsValidator = null;
465
466                 if (!adminRolesService.isSuperAdmin(user)) {
467                         EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
468                 } else {
469                         fieldsValidator = functionalMenuService.regenerateAncestorTable();
470                         response.setStatus(fieldsValidator.httpStatusCode.intValue());
471                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/regenerateAncestorTable", "GET result =",
472                                         response.getStatus());
473                 }
474
475                 return fieldsValidator;
476         }
477
478         /**
479          * RESful service to set a favorite item.
480          *
481          * @param request
482          *            HttpServletRequest
483          * @param response
484          *            HttpServletResponse
485          * @param menuItemJson
486          *            FunctionalMenuItemWithRoles
487          * @return FieldsValidator
488          */
489         @PostMapping(value = { "/portalApi/setFavoriteItem" })
490         public FieldsValidator addFavoriteItem(HttpServletRequest request,
491                         @RequestBody FavoritesFunctionalMenuItem menuItemJson, HttpServletResponse response) {
492                 EPUser user = EPUserUtils.getUserSession(request);
493                 FieldsValidator fieldsValidator = null;
494                 menuItemJson.userId = user.getId();
495                 fieldsValidator = functionalMenuService.setFavoriteItem(menuItemJson);
496                 response.setStatus(fieldsValidator.httpStatusCode.intValue());
497                 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/setFavoriteItem", "Post result =",
498                                 response.getStatus());
499
500                 return fieldsValidator;
501         }
502
503         /**
504          * RESTful service to get favorites for the current user as identified in the
505          * session
506          *
507          * @param request
508          *            HttpServletRequest
509          * @param response
510          *            HttpServletResponse
511          * @return List of FavoritesFunctionalMenuItemJson
512          */
513         @GetMapping(value = {
514                         "/portalApi/getFavoriteItems" }, produces = "application/json")
515         public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
516                         HttpServletResponse response) {
517                 EPUser user = EPUserUtils.getUserSession(request);
518                 List<FavoritesFunctionalMenuItemJson> favorites = functionalMenuService.getFavoriteItems(user.getId());
519                 FieldsValidator fieldsValidator = new FieldsValidator();
520                 response.setStatus(fieldsValidator.httpStatusCode.intValue());
521                 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getFavoriteItems", "GET result =",
522                                 response.getStatus());
523                 return favorites;
524         }
525
526         /**
527          * RESTful service to delete a favorite menu item for the current user as
528          * identified in the session.
529          *
530          * @param request
531          *            HttpServletRequest
532          * @param response
533          *            HttpServletResponse
534          * @param menuId
535          *            menu identifier
536          * @return FieldsValidator
537          */
538         @DeleteMapping(value = { "/portalApi/removeFavoriteItem/{menuId}" })
539         public FieldsValidator deleteFavoriteItem(HttpServletRequest request, @PathVariable("menuId") Long menuId,
540                         HttpServletResponse response) {
541                 EPUser user = EPUserUtils.getUserSession(request);
542                 FieldsValidator fieldsValidator = null;
543                 Long userId = user.getId();
544                 fieldsValidator = functionalMenuService.removeFavoriteItem(userId, menuId);
545                 response.setStatus(fieldsValidator.httpStatusCode.intValue());
546                 EcompPortalUtils.logAndSerializeObject(logger, "/deleteFavoriteItem", "DELETE result =", response.getStatus());
547
548                 return fieldsValidator;
549         }
550
551         /**
552          * RESTful service to get user information: user's first and last names, org
553          * user ID, email and last-login. (Actually has nothing to do with the real
554          * functional menu.) First attempts to get the information from the Tomcat
555          * session (i.e., the CSP cookie); if that fails, calls the shared context
556          * service to read the information from the database. Gives back what it found,
557          * any of which may be null, as a JSON collection.
558          *
559          * @param request
560          *            HttpServletRequest
561          * @param response
562          *            HttpServletResponse
563          * @return JSON collection of key-value pairs shown below.
564          */
565         @GetMapping(value = {
566                         "/portalApi/functionalMenuStaticInfo" }, produces = "application/json")
567         public String getFunctionalMenuStaticInfo(HttpServletRequest request, HttpServletResponse response) {
568
569                 // Get user details from session
570                 logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuStaticInfo: getting user info");
571                 String fnMenuStaticResponse = null;
572                 try {
573                         String orgUserIdStr = null, firstNameStr = null, lastNameStr = null, emailStr = null, lastLogin = null;
574                         EPUser user = EPUserUtils.getUserSession(request);
575                         firstNameStr = user.getFirstName();
576                         lastNameStr = user.getLastName();
577                         orgUserIdStr = user.getOrgUserId();
578                         emailStr = user.getEmail();
579                         if (emailStr == null || emailStr.equals("")) {
580                                 EPUser userResult = searchService.searchUserByUserId(orgUserIdStr);
581                                 emailStr = userResult.getEmail();
582                         }
583                         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss Z a");
584                         Date lastLoginDate = user.getLastLoginDate();
585                         if (lastLoginDate == null) {
586                                 // should never happen
587                                 logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo: no last login in session");
588                                 lastLogin = "no last login available";
589                         } else {
590                                 lastLogin = sdf.format(lastLoginDate);
591                         }
592
593                         // If any item is missing from session, try the Shared Context
594                         // service.
595                         SharedContext orgUserIdSC = null, firstNameSC = null, lastNameSC = null, emailSC = null;
596                         String sessionId = request.getSession().getId();
597                         if (firstNameStr == null)
598                                 firstNameSC = sharedContextService.getSharedContext(sessionId,
599                                                 EPCommonSystemProperties.USER_FIRST_NAME);
600                         if (lastNameStr == null)
601                                 lastNameSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_LAST_NAME);
602                         if (emailStr == null)
603                                 emailSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_EMAIL);
604                         if (orgUserIdStr == null)
605                                 orgUserIdSC = sharedContextService.getSharedContext(sessionId,
606                                                 EPCommonSystemProperties.USER_ORG_USERID);
607
608                         // Build the response
609                         Map<String, String> map = new HashMap<String, String>();
610                         map.put("firstName",
611                                         firstNameStr != null ? firstNameStr : (firstNameSC != null ? firstNameSC.getCvalue() : null));
612                         map.put("lastName",
613                                         lastNameStr != null ? lastNameStr : (lastNameSC != null ? lastNameSC.getCvalue() : null));
614                         map.put("email", emailStr != null ? emailStr : (emailSC != null ? emailSC.getCvalue() : null));
615                         map.put("userId",
616                                         orgUserIdStr != null ? orgUserIdStr : (orgUserIdSC != null ? orgUserIdSC.getCvalue() : null));
617                         map.put("last_login", lastLogin);
618                         JSONObject j = new JSONObject(map);
619                         fnMenuStaticResponse = j.toString();
620                         // Be chatty in the log
621                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuStaticInfo", "GET result =",
622                                         fnMenuStaticResponse);
623                 } catch (Exception e) {
624                         // Should never happen.
625                         logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo failed", e);
626                         // Return a real error?
627                         // fnMenuStaticResponse = "{ \"status\": \"error\", \"message\": \""
628                         // + e.toString() + "\" }";
629                         // But the angular controller expects null on error.
630                 }
631                 return fnMenuStaticResponse;
632         }
633
634         private Comparator<BusinessCardApplicationRole> getUserAppRolesComparator = new Comparator<BusinessCardApplicationRole>() {
635                 public int compare(BusinessCardApplicationRole o1, BusinessCardApplicationRole o2) {
636                         return o1.getAppName().compareTo(o2.getAppName());
637                 }
638         };
639
640         /**
641          *
642          * @param request
643          *            HttpServletRequest
644          * @param userId
645          *            user ID
646          * @return List<BusinessCardApplicationRolesList>
647          * @throws IOException
648          *             on error
649          */
650         @GetMapping(value = {
651                         "/portalApi/userApplicationRoles" }, produces = "application/json")
652         public List<BusinessCardApplicationRolesList> getAppList(HttpServletRequest request, HttpServletResponse response,
653                         @RequestParam("userId") String userId) throws IOException {
654
655                 List<BusinessCardApplicationRolesList> AppRoles = null;
656                 
657                 if(!UserUtils.getUserSession(request).getOrgUserId().equalsIgnoreCase(userId)) {
658                         logger.error(EELFLoggerDelegate.errorLogger, "Not authorized to view roles of others ");
659                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
660                         response.getWriter().flush();
661                         return null;
662                 }
663                         
664                 try {
665                         List<BusinessCardApplicationRole> userAppRoleList = functionalMenuService.getUserAppRolesList(userId);
666
667                         Collections.sort(userAppRoleList, getUserAppRolesComparator);
668                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =",
669                                         userAppRoleList);
670
671                         AppRoles = new ArrayList<BusinessCardApplicationRolesList>();
672                         for (BusinessCardApplicationRole userAppRole : userAppRoleList) {
673                                 boolean found = false;
674                                 List<String> roles = null;
675
676                                 for (BusinessCardApplicationRolesList app : AppRoles) {
677                                         if (app.getAppName().equals(userAppRole.getAppName())) {
678                                                 roles = app.getRoleNames();
679                                                 roles.add(userAppRole.getRoleName());
680                                                 app.setRoleNames(roles);
681                                                 found = true;
682                                                 break;
683                                         }
684                                 }
685
686                                 if (!found) {
687                                         roles = new ArrayList<String>();
688                                         roles.add(userAppRole.getRoleName());
689                                         AppRoles.add(new BusinessCardApplicationRolesList(userAppRole.getAppName(), roles));
690                                 }
691
692                                 Collections.sort(roles);
693                         }
694                 } catch (Exception e) {
695                         logger.error(EELFLoggerDelegate.errorLogger, "getAppList failed", e);
696                 }
697
698                 return AppRoles;
699
700         }
701 }