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