2 * ================================================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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 * ================================================================================
20 package org.openecomp.portalapp.portal.controller;
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;
31 import javax.servlet.http.HttpServletRequest;
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;
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;
64 * Controller supplies data to Angular services on the dashboard page.
68 @RequestMapping("/portalApi/dashboard")
69 public class DashboardController extends EPRestrictedBaseController {
71 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
74 private DashboardSearchService searchService;
76 private AuditService auditService;
78 public enum WidgetCategory {
79 EVENTS, NEWS, IMPORTANTRESOURCES;
83 * Validates the resource type parameter.
86 * @return True if known in the enum WidgetCategory, else false.
88 private boolean isValidResourceType(String resourceType) {
89 if (resourceType == null)
91 for (WidgetCategory wc : WidgetCategory.values())
92 if (wc.name().equals(resourceType))
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)
102 * @param resourceType
104 * @return Rest response wrapped around a CommonWidgetMeta object.
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));
118 * Saves a batch of events, news or resources.
120 * @param commonWidgetMeta
121 * read from POST body.
122 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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);
134 for (CommonWidget cw : commonWidgetMeta.getItems()) {
135 String err = validateCommonWidget(cw);
137 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
139 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
140 searchService.saveWidgetDataBulk(commonWidgetMeta));
144 * Saves one: event, news or resource
146 * @param commonWidget
147 * read from POST body
148 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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);
158 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
159 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
160 searchService.saveWidgetData(commonWidget));
164 * Used by the validate function
166 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
169 * Validates the content of a common widget.
172 * @return null on success; an error message if validation fails.
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";
190 yearMonthDayFormat.setLenient(false);
191 Date date = yearMonthDayFormat.parse(cw.getEventDate());
193 return "Failed to parse date " + cw.getEventDate();
194 } catch (ParseException ex) {
195 return ex.toString();
202 * Deletes one: event, news or resource
204 * @param commonWidget
205 * read from POST body
206 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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));
216 * Searches all portal for the input string.
219 * @param searchString
220 * @return Rest response wrapped around a Map of String to List of Search
224 @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
225 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
226 @RequestParam String searchString) {
228 if (searchString != null)
229 searchString = searchString.trim();
230 EPUser user = EPUserUtils.getUserSession(request);
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>>());
240 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
241 user.getLoginId(), searchString);
242 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
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);
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>>());
268 * Gets all active users.
270 * TODO: should only the superuser be allowed to use this API?
273 * @return Rest response wrapped around a list of String
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<>();
280 EPUser user = EPUserUtils.getUserSession(request);
281 String userId = user.getOrgUserId();
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);
291 } catch (Exception e) {
292 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
298 * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
301 * @return Rest response wrapped around a number that is the number of milliseconds.
303 @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
304 public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
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);
321 * Gets the window width threshold for collapsing right menu from system.properties.
324 * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
326 @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
327 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
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);
342 * Gets the window width threshold for collapsing left menu from system.properties.
345 * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
347 @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
348 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
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);
362 * Gets only those users that are 'related' to the currently logged-in user.
365 * @return Rest response wrapped around a List of String
367 @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
368 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
369 EPUser user = EPUserUtils.getUserSession(request);
372 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
375 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
376 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
377 searchService.getRelatedUsers(user.getLoginId()));
379 } catch (Exception e) {
380 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
381 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",