2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.onap.portalapp.portal.controller;
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;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
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;
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;
84 * Controller supplies data to Angular services on the dashboard page.
88 @RequestMapping("/portalApi/dashboard")
89 public class DashboardController extends EPRestrictedBaseController {
91 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
94 private DashboardSearchService searchService;
96 private AuditService auditService;
99 private AdminRolesService adminRolesService;
101 public enum WidgetCategory {
102 EVENTS, NEWS, IMPORTANTRESOURCES;
106 * Validates the resource type parameter.
108 * @param resourceType
109 * @return True if known in the enum WidgetCategory, else false.
111 private boolean isValidResourceType(String resourceType) {
112 if (resourceType == null)
114 for (WidgetCategory wc : WidgetCategory.values())
115 if (wc.name().equals(resourceType))
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)
125 * @param resourceType
127 * @return Rest response wrapped around a CommonWidgetMeta object.
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));
141 * Saves a batch of events, news or resources.
143 * @param commonWidgetMeta
144 * read from POST body.
145 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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);
157 for (CommonWidget cw : commonWidgetMeta.getItems()) {
158 String err = validateCommonWidget(cw);
160 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
162 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
163 searchService.saveWidgetDataBulk(commonWidgetMeta));
167 * Saves one: event, news or resource
169 * @param commonWidget
170 * read from POST body
171 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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);
184 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
185 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
186 searchService.saveWidgetData(commonWidget));
188 EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
189 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed", null);
194 * Used by the validate function
196 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
199 * Validates the content of a common widget.
202 * @return null on success; an error message if validation fails.
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";
219 yearMonthDayFormat.setLenient(false);
220 Date date = yearMonthDayFormat.parse(cw.getEventDate());
222 return "Failed to parse date " + cw.getEventDate();
223 } catch (ParseException ex) {
224 return "Invalid date format " +ex.toString();
230 * Deletes one: event, news or resource
232 * @param commonWidget
233 * read from POST body
234 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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));
244 * Searches all portal for the input string.
247 * @param searchString
248 * @return Rest response wrapped around a Map of String to List of Search
252 @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
253 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
254 @RequestParam String searchString) {
256 if (searchString != null)
257 searchString = searchString.trim();
258 EPUser user = EPUserUtils.getUserSession(request);
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>>());
268 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
269 user.getLoginId(), searchString);
270 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
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);
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>>());
296 * Gets all active users.
298 * TODO: should only the superuser be allowed to use this API?
301 * @return Rest response wrapped around a list of String
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<>();
308 EPUser user = EPUserUtils.getUserSession(request);
309 String userId = user.getOrgUserId();
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);
319 } catch (Exception e) {
320 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
326 * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
329 * @return Rest response wrapped around a number that is the number of milliseconds.
331 @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
332 public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
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);
349 * Gets the window width threshold for collapsing right menu from system.properties.
352 * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
354 @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
355 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
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);
370 * Gets the window width threshold for collapsing left menu from system.properties.
373 * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
375 @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
376 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
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);
390 * Gets only those users that are 'related' to the currently logged-in user.
393 * @return Rest response wrapped around a List of String
395 @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
396 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
397 EPUser user = EPUserUtils.getUserSession(request);
400 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
403 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
404 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
405 searchService.getRelatedUsers(user.getLoginId()));
407 } catch (Exception e) {
408 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
409 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",