17a2847672406723009550cd665eca32c18b311a
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / DashboardController.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.text.ParseException;
41 import java.text.SimpleDateFormat;
42 import java.util.ArrayList;
43 import java.util.Date;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.List;
47 import java.util.Map;
48
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
52 import org.onap.portalapp.controller.EPRestrictedBaseController;
53 import org.onap.portalapp.portal.domain.EPUser;
54 import org.onap.portalapp.portal.domain.EcompAuditLog;
55 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
56 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
57 import org.onap.portalapp.portal.ecomp.model.SearchResultItem;
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.DashboardSearchService;
63 import org.onap.portalapp.portal.transport.CommonWidget;
64 import org.onap.portalapp.portal.transport.CommonWidgetMeta;
65 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
66 import org.onap.portalapp.portal.utils.EcompPortalUtils;
67 import org.onap.portalapp.portal.utils.PortalConstants;
68 import org.onap.portalapp.util.EPUserUtils;
69 import org.onap.portalapp.validation.DataValidator;
70 import org.onap.portalapp.validation.SecureString;
71 import org.onap.portalsdk.core.domain.AuditLog;
72 import org.onap.portalsdk.core.domain.support.CollaborateList;
73 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
74 import org.onap.portalsdk.core.service.AuditService;
75 import org.onap.portalsdk.core.util.SystemProperties;
76 import org.slf4j.MDC;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.context.annotation.Configuration;
79 import org.springframework.web.bind.annotation.RequestBody;
80 import org.springframework.web.bind.annotation.RequestMapping;
81 import org.springframework.web.bind.annotation.GetMapping;
82 import org.springframework.web.bind.annotation.PostMapping;
83 import org.springframework.web.bind.annotation.PutMapping;
84 import org.springframework.web.bind.annotation.DeleteMapping;
85 import org.springframework.web.bind.annotation.RequestMethod;
86 import org.springframework.web.bind.annotation.RequestParam;
87 import org.springframework.web.bind.annotation.RestController;
88
89 /**
90  * Controller supplies data to Angular services on the dashboard page.
91  */
92 @Configuration
93 @RestController
94 @RequestMapping("/portalApi/dashboard")
95 public class DashboardController extends EPRestrictedBaseController {
96         private static final DataValidator DATA_VALIDATOR = new DataValidator();
97         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
98
99         private DashboardSearchService searchService;
100         private AuditService auditService;
101         private AdminRolesService adminRolesService;
102
103         @Autowired
104         public DashboardController(DashboardSearchService searchService,
105                 AuditService auditService, AdminRolesService adminRolesService) {
106                 this.searchService = searchService;
107                 this.auditService = auditService;
108                 this.adminRolesService = adminRolesService;
109         }
110
111         public enum WidgetCategory {
112                 EVENTS, NEWS, IMPORTANTRESOURCES
113         }
114
115         /**
116          * Validates the resource type parameter.
117          * 
118          * @param resourceType
119          * @return True if known in the enum WidgetCategory, else false.
120          */
121         private boolean isValidResourceType(String resourceType) {
122                 if (resourceType == null)
123                         return false;
124                 for (WidgetCategory wc : WidgetCategory.values())
125                         if (wc.name().equals(resourceType))
126                                 return true;
127                 return false;
128         }
129
130         /**
131          * Gets all widgets of the specified resource type. 
132          * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
133          * 
134          * @param request
135          * @param resourceType
136          *            Request parameter.
137          * @return Rest response wrapped around a CommonWidgetMeta object.
138          */
139         @GetMapping(value = "/widgetData", produces = "application/json")
140         public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
141                         @RequestParam String resourceType) {
142                 if (!isValidResourceType(resourceType)) {
143                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
144                                 "Unexpected resource type " + resourceType, null);
145                 }else if (!DATA_VALIDATOR.isValid(new SecureString(resourceType))){
146                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
147                                 "Unsafe resource type " + resourceType, null);
148                 }
149                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
150                         searchService.getWidgetData(resourceType));
151         }
152         
153         
154         /**
155          * Saves a batch of events, news or resources.
156          * 
157          * @param commonWidgetMeta
158          *            read from POST body.
159          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
160          */
161         @PostMapping(value = "/widgetDataBulk", produces = "application/json")
162         public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
163                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
164                 if (!DATA_VALIDATOR.isValid(commonWidgetMeta)){
165                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
166                                 "Unsafe resource type " + commonWidgetMeta, "ERROR");
167                 }else if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) {
168                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
169                                 "Category cannot be null or empty");
170                 }else if (!isValidResourceType(commonWidgetMeta.getCategory())) {
171                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
172                                 "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
173                 }
174                 for (CommonWidget cw : commonWidgetMeta.getItems()) {
175                         String err = validateCommonWidget(cw);
176                         if (err != null)
177                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
178                 }
179                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
180                         searchService.saveWidgetDataBulk(commonWidgetMeta));
181         }
182
183         /**
184          * Saves one: event, news or resource
185          * 
186          * @param commonWidget
187          *            read from POST body
188          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
189          */
190         @PostMapping(value = "/widgetData", produces = "application/json")
191         public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget, HttpServletRequest request, HttpServletResponse response) {
192                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
193                 EPUser user = EPUserUtils.getUserSession(request);
194                 if (adminRolesService.isSuperAdmin(user)) {
195                         if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().isEmpty()) {
196                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
197                                         "Category cannot be null or empty");
198                         }else if (!DATA_VALIDATOR.isValid(commonWidget)){
199                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
200                                         "Unsafe resource type " + commonWidget, "ERROR");
201                         }
202                         String err = validateCommonWidget(commonWidget);
203                         if (err != null)
204                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
205                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
206                                 searchService.saveWidgetData(commonWidget));
207                 } else {
208                         EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
209                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed", null);
210                 }
211         }
212
213         /**
214          * Used by the validate function
215          */
216         private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
217
218         /**
219          * Validates the content of a common widget.
220          * 
221          * @param cw
222          * @return null on success; an error message if validation fails.
223          * @throws Exception
224          */
225         private String validateCommonWidget(CommonWidget cw) {
226                 if (!isValidResourceType(cw.getCategory()))
227                         return "Invalid category: " + cw.getCategory();
228                 if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
229                         return "Title is missing";
230                 if (cw.getHref() == null || cw.getHref().trim().length() == 0)
231                         return "HREF is missing";
232                 if (!cw.getHref().toLowerCase().startsWith("http"))
233                         return "HREF does not start with http";
234                 if (cw.getSortOrder() == null)
235                         return "Sort order is null";
236                 if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
237                         return "Date is missing";
238                 try {
239                         yearMonthDayFormat.setLenient(false);
240                         Date date = yearMonthDayFormat.parse(cw.getEventDate());
241                         if (date == null)
242                                 return "Failed to parse date " + cw.getEventDate();
243                 } catch (ParseException ex) {
244                         return "Invalid date format " +ex.toString();
245                 }
246                 return null;
247         }
248
249         /**
250          * Deletes one: event, news or resource
251          * 
252          * @param commonWidget
253          *            read from POST body
254          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
255          */
256         @PostMapping(value = "/deleteData", produces = "application/json")
257         public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
258                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
259                 if (!DATA_VALIDATOR.isValid(commonWidget)){
260                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
261                                 "Unsafe resource type " + commonWidget, "ERROR");
262                 }
263                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
264                         searchService.deleteWidgetData(commonWidget));
265         }
266
267         /**
268          * Searches all portal for the input string.
269          * 
270          * @param request
271          * @param searchString
272          * @return Rest response wrapped around a Map of String to List of Search
273          *         Result Item.
274          */
275         @EPAuditLog
276         @GetMapping(value = "/search", produces = "application/json")
277         public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
278                         @RequestParam String searchString) {
279                 if (!DATA_VALIDATOR.isValid(new SecureString(searchString))){
280                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not safe",
281                                 new HashMap<>());
282                 }
283                 if (searchString != null)
284                         searchString = searchString.trim();
285                 EPUser user = EPUserUtils.getUserSession(request);
286                 try {
287                         if (user == null) {
288                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
289                                                 "searchPortal: User object is null? - check logs",
290                                         new HashMap<>());
291                         } else if (searchString == null || searchString.length() == 0) {
292                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
293                                         new HashMap<>());
294                         } else {
295                                 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
296                                                 user.getLoginId(), searchString);
297                                 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
298                                                 searchString);
299                                 /*Audit log the search*/
300                                 AuditLog auditLog = new AuditLog();
301                                 auditLog.setUserId(user.getId());
302                                 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
303                                 auditLog.setComments(EcompPortalUtils.truncateString(searchString, PortalConstants.AUDIT_LOG_COMMENT_SIZE));
304                                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());  
305                                 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE);
306                                 MDC.put(com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
307                                 auditService.logActivity(auditLog, null);
308                                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
309                                 
310                                 MDC.put(EPCommonSystemProperties.STATUS_CODE, "COMPLETE");
311                                 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
312                                 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse", 
313                                                 EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));    
314                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
315                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
316                                 MDC.remove(SystemProperties.MDC_TIMER);
317                                 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
318                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
319                         }
320                 } catch (Exception e) {
321                         logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
322                         MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
323                         MDC.remove(EPCommonSystemProperties.STATUS_CODE);
324                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
325                                 new HashMap<>());
326                 }
327         }
328
329         /**
330          * Gets all active users.
331          * 
332          * TODO: should only the superuser be allowed to use this API?
333          * 
334          * @param request
335          * @return Rest response wrapped around a list of String
336          */
337         @GetMapping(value = "/activeUsers", produces = "application/json")
338         public List<String> getActiveUsers(HttpServletRequest request) {
339                 List<String> activeUsers;
340                 List<String> onlineUsers = new ArrayList<>();
341                 try {
342                         EPUser user = EPUserUtils.getUserSession(request);
343                         String userId = user.getOrgUserId();
344
345                         activeUsers = searchService.getRelatedUsers(userId);
346                         HashSet<String> usersSet = (HashSet<String>) CollaborateList.getInstance().getAllUserName();
347                         for (String users : activeUsers) {
348                                 if (usersSet.contains(users)) {
349                                         onlineUsers.add(users);
350                                 }
351                         }
352
353                 } catch (Exception e) {
354                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
355                 }
356                 return onlineUsers;
357         }
358         
359         /**
360          * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
361          * 
362          * @param request
363          * @return Rest response wrapped around a number that is the number of milliseconds.
364          */
365         @GetMapping(value = "/onlineUserUpdateRate", produces = "application/json")
366         public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
367                 try {
368                         String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);     
369                         String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);                             
370                         Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
371                         Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
372                         Map<String, String> results = new HashMap<>();
373                         results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
374                         results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));                     
375                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
376                 } catch (Exception e) {
377                         logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
378                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
379                 }               
380         }
381
382         /**
383          * Gets the window width threshold for collapsing right menu from system.properties.
384          * 
385          * @param request
386          * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
387          */
388         @GetMapping(value = "/windowWidthThresholdRightMenu", produces = "application/json")
389         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
390                 try {
391                         String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);    
392                         Integer windowWidth = Integer.valueOf(windowWidthString);
393                         Map<String, String> results = new HashMap<>();
394                         results.put("windowWidth", String.valueOf(windowWidth));
395                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
396                 } catch (Exception e) {
397                         logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
398                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
399                 }               
400         }
401
402
403         /**
404          * Gets the window width threshold for collapsing left menu from system.properties.
405          * 
406          * @param request
407          * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
408          */
409         @GetMapping(value = "/windowWidthThresholdLeftMenu", produces = "application/json")
410         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
411                 try {
412                         String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);     
413                         Integer windowWidth = Integer.valueOf(windowWidthString);
414                         Map<String, String> results = new HashMap<>();
415                         results.put("windowWidth", String.valueOf(windowWidth));
416                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
417                 } catch (Exception e) {
418                         logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
419                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
420                 }               
421         }
422         
423         /**
424          * Gets only those users that are 'related' to the currently logged-in user.
425          * 
426          * @param request
427          * @return Rest response wrapped around a List of String
428          */
429         @GetMapping(value = "/relatedUsers", produces = "application/json")
430         public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
431                 EPUser user = EPUserUtils.getUserSession(request);
432                 try {
433                         if (user == null) {
434                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
435                                                 new ArrayList<>());
436                         } else {
437                                 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
438                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
439                                                 searchService.getRelatedUsers(user.getLoginId()));
440                         }
441                 } catch (Exception e) {
442                         logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
443                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
444                                         new ArrayList<>());
445                 }
446         }
447
448 }