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