1c22576d9069ea3ba24201ab46c6bc1da90d3c15
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / controller / DashboardController.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.controller;
21
22 import java.text.ParseException;
23 import java.text.SimpleDateFormat;
24 import java.util.ArrayList;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.servlet.http.HttpServletRequest;
32
33 import org.openecomp.portalapp.controller.EPRestrictedBaseController;
34 import org.openecomp.portalapp.portal.domain.EPUser;
35 import org.openecomp.portalapp.portal.domain.EcompAuditLog;
36 import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
37 import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
38 import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
39 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
40 import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
41 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
42 import org.openecomp.portalapp.portal.service.DashboardSearchService;
43 import org.openecomp.portalapp.portal.transport.CommonWidget;
44 import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
45 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
46 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
47 import org.openecomp.portalapp.portal.utils.PortalConstants;
48 import org.openecomp.portalapp.util.EPUserUtils;
49 import org.openecomp.portalsdk.core.domain.AuditLog;
50 import org.openecomp.portalsdk.core.domain.support.CollaborateList;
51 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
52 import org.openecomp.portalsdk.core.service.AuditService;
53 import org.openecomp.portalsdk.core.util.SystemProperties;
54 import org.slf4j.MDC;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.context.annotation.Configuration;
57 import org.springframework.web.bind.annotation.RequestBody;
58 import org.springframework.web.bind.annotation.RequestMapping;
59 import org.springframework.web.bind.annotation.RequestMethod;
60 import org.springframework.web.bind.annotation.RequestParam;
61 import org.springframework.web.bind.annotation.RestController;
62
63 /**
64  * Controller supplies data to Angular services on the dashboard page.
65  */
66 @Configuration
67 @RestController
68 @RequestMapping("/portalApi/dashboard")
69 public class DashboardController extends EPRestrictedBaseController {
70
71         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
72
73         @Autowired
74         private DashboardSearchService searchService;
75         @Autowired
76         private AuditService auditService;
77         
78         public enum WidgetCategory {
79                 EVENTS, NEWS, IMPORTANTRESOURCES;
80         }
81
82         /**
83          * Validates the resource type parameter.
84          * 
85          * @param resourceType
86          * @return True if known in the enum WidgetCategory, else false.
87          */
88         private boolean isValidResourceType(String resourceType) {
89                 if (resourceType == null)
90                         return false;
91                 for (WidgetCategory wc : WidgetCategory.values())
92                         if (wc.name().equals(resourceType))
93                                 return true;
94                 return false;
95         }
96
97         /**
98          * Gets all widgets of the specified resource type. 
99          * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
100          * 
101          * @param request
102          * @param resourceType
103          *            Request parameter.
104          * @return Rest response wrapped around a CommonWidgetMeta object.
105          */
106         @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
107         public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
108                         @RequestParam String resourceType) {
109                 if (!isValidResourceType(resourceType))
110                         return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.ERROR,
111                                         "Unexpected resource type " + resourceType, null);
112                 return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
113                                 searchService.getWidgetData(resourceType));
114         }
115         
116         
117         /**
118          * Saves a batch of events, news or resources.
119          * 
120          * @param commonWidgetMeta
121          *            read from POST body.
122          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
123          */
124         @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
125         public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
126                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
127                 if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
128                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
129                                         "Category cannot be null or empty");
130                 if (!isValidResourceType(commonWidgetMeta.getCategory()))
131                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
132                                         "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
133                 // validate dates
134                 for (CommonWidget cw : commonWidgetMeta.getItems()) {
135                         String err = validateCommonWidget(cw);
136                         if (err != null)
137                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
138                 }
139                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
140                                 searchService.saveWidgetDataBulk(commonWidgetMeta));
141         }
142
143         /**
144          * Saves one: event, news or resource
145          * 
146          * @param commonWidget
147          *            read from POST body
148          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
149          */
150         @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
151         public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
152                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
153                 if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals(""))
154                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
155                                         "Category cannot be null or empty");
156                 String err = validateCommonWidget(commonWidget);
157                 if (err != null)
158                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
159                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
160                                 searchService.saveWidgetData(commonWidget));
161         }
162
163         /**
164          * Used by the validate function
165          */
166         private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
167
168         /**
169          * Validates the content of a common widget.
170          * 
171          * @param cw
172          * @return null on success; an error message if validation fails.
173          * @throws Exception
174          */
175         private String validateCommonWidget(CommonWidget cw) {
176                 if (!isValidResourceType(cw.getCategory()))
177                         return "Invalid category: " + cw.getCategory();
178                 if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
179                         return "Title is missing";
180                 if (cw.getHref() == null || cw.getHref().trim().length() == 0)
181                         return "HREF is missing";
182                 if (!cw.getHref().toLowerCase().startsWith("http"))
183                         return "HREF does not start with http";
184                 if (cw.getSortOrder() == null)
185                         return "Sort order is null";
186                 if (WidgetCategory.EVENTS.name().equals(cw.getCategory())) {
187                         if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
188                                 return "Date is missing";
189                         try {
190                                 yearMonthDayFormat.setLenient(false);
191                                 Date date = yearMonthDayFormat.parse(cw.getEventDate());
192                                 if (date == null)
193                                         return "Failed to parse date " + cw.getEventDate();
194                         } catch (ParseException ex) {
195                                 return ex.toString();
196                         }
197                 }
198                 return null;
199         }
200
201         /**
202          * Deletes one: event, news or resource
203          * 
204          * @param commonWidget
205          *            read from POST body
206          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
207          */
208         @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
209         public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
210                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
211                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
212                                 searchService.deleteWidgetData(commonWidget));
213         }
214
215         /**
216          * Searches all portal for the input string.
217          * 
218          * @param request
219          * @param searchString
220          * @return Rest response wrapped around a Map of String to List of Search
221          *         Result Item.
222          */
223         @EPAuditLog
224         @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
225         public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
226                         @RequestParam String searchString) {
227
228                 if (searchString != null)
229                         searchString = searchString.trim();
230                 EPUser user = EPUserUtils.getUserSession(request);
231                 try {
232                         if (user == null) {
233                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
234                                                 "searchPortal: User object is null? - check logs",
235                                                 new HashMap<String, List<SearchResultItem>>());
236                         } else if (searchString == null || searchString.length() == 0) {
237                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
238                                                 new HashMap<String, List<SearchResultItem>>());
239                         } else {
240                                 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
241                                                 user.getLoginId(), searchString);
242                                 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
243                                                 searchString);
244                                 /*Audit log the search*/
245                                 AuditLog auditLog = new AuditLog();
246                                 auditLog.setUserId(user.getId());
247                                 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
248                                 auditLog.setComments(EcompPortalUtils.truncateString(searchString, PortalConstants.AUDIT_LOG_COMMENT_SIZE));
249                                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());          
250                                 auditService.logActivity(auditLog, null);
251                                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
252                                 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
253                                 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse", 
254                                                 EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));    
255                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
256                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
257                                 MDC.remove(SystemProperties.MDC_TIMER);
258                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
259                         }
260                 } catch (Exception e) {
261                         logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
262                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
263                                         new HashMap<String, List<SearchResultItem>>());
264                 }
265         }
266
267         /**
268          * Gets all active users.
269          * 
270          * TODO: should only the superuser be allowed to use this API?
271          * 
272          * @param request
273          * @return Rest response wrapped around a list of String
274          */
275         @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
276         public List<String> getActiveUsers(HttpServletRequest request) {
277                 List<String> activeUsers = null;
278                 List<String> onlineUsers = new ArrayList<>();
279                 try {
280                         EPUser user = EPUserUtils.getUserSession(request);
281                         String userId = user.getOrgUserId();
282
283                         activeUsers = searchService.getRelatedUsers(userId);
284                         HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName();
285                         for (String users : activeUsers) {
286                                 if (usersSet.contains(users)) {
287                                         onlineUsers.add(users);
288                                 }
289                         }
290
291                 } catch (Exception e) {
292                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
293                 }
294                 return onlineUsers;
295         }
296         
297         /**
298          * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
299          * 
300          * @param request
301          * @return Rest response wrapped around a number that is the number of milliseconds.
302          */
303         @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
304         public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
305                 try {
306                         String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);     
307                         String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);                             
308                         Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
309                         Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
310                         Map<String, String> results = new HashMap<String,String>();
311                         results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
312                         results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));                     
313                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
314                 } catch (Exception e) {
315                         logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
316                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
317                 }               
318         }
319
320         /**
321          * Gets the window width threshold for collapsing right menu from system.properties.
322          * 
323          * @param request
324          * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
325          */
326         @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
327         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
328                 try {
329                         String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);    
330                         Integer windowWidth = Integer.valueOf(windowWidthString);
331                         Map<String, String> results = new HashMap<String,String>();
332                         results.put("windowWidth", String.valueOf(windowWidth));
333                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
334                 } catch (Exception e) {
335                         logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
336                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
337                 }               
338         }
339
340
341         /**
342          * Gets the window width threshold for collapsing left menu from system.properties.
343          * 
344          * @param request
345          * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
346          */
347         @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
348         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
349                 try {
350                         String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);     
351                         Integer windowWidth = Integer.valueOf(windowWidthString);
352                         Map<String, String> results = new HashMap<String,String>();
353                         results.put("windowWidth", String.valueOf(windowWidth));
354                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
355                 } catch (Exception e) {
356                         logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
357                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
358                 }               
359         }
360         
361         /**
362          * Gets only those users that are 'related' to the currently logged-in user.
363          * 
364          * @param request
365          * @return Rest response wrapped around a List of String
366          */
367         @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
368         public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
369                 EPUser user = EPUserUtils.getUserSession(request);
370                 try {
371                         if (user == null) {
372                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
373                                                 new ArrayList<>());
374                         } else {
375                                 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
376                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
377                                                 searchService.getRelatedUsers(user.getLoginId()));
378                         }
379                 } catch (Exception e) {
380                         logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
381                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
382                                         new ArrayList<>());
383                 }
384         }
385
386 }