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============================================
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.portalapp.validation.DataValidator;
70 import org.onap.portalapp.validation.SecureString;
71 import org.onap.portalsdk.core.domain.AuditLog;
72 import org.onap.portalsdk.core.domain.support.CollaborateList;
73 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
74 import org.onap.portalsdk.core.service.AuditService;
75 import org.onap.portalsdk.core.util.SystemProperties;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.context.annotation.Configuration;
79 import org.springframework.web.bind.annotation.RequestBody;
80 import org.springframework.web.bind.annotation.RequestMapping;
81 import org.springframework.web.bind.annotation.RequestMethod;
82 import org.springframework.web.bind.annotation.RequestParam;
83 import org.springframework.web.bind.annotation.RestController;
86 * Controller supplies data to Angular services on the dashboard page.
90 @RequestMapping("/portalApi/dashboard")
91 public class DashboardController extends EPRestrictedBaseController {
92 private static final DataValidator DATA_VALIDATOR = new DataValidator();
93 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
95 private DashboardSearchService searchService;
96 private AuditService auditService;
97 private AdminRolesService adminRolesService;
100 public DashboardController(DashboardSearchService searchService,
101 AuditService auditService, AdminRolesService adminRolesService) {
102 this.searchService = searchService;
103 this.auditService = auditService;
104 this.adminRolesService = adminRolesService;
107 public enum WidgetCategory {
108 EVENTS, NEWS, IMPORTANTRESOURCES
112 * Validates the resource type parameter.
114 * @param resourceType
115 * @return True if known in the enum WidgetCategory, else false.
117 private boolean isValidResourceType(String resourceType) {
118 if (resourceType == null)
120 for (WidgetCategory wc : WidgetCategory.values())
121 if (wc.name().equals(resourceType))
127 * Gets all widgets of the specified resource type.
128 * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
131 * @param resourceType
133 * @return Rest response wrapped around a CommonWidgetMeta object.
135 @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
136 public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
137 @RequestParam String resourceType) {
138 if (!isValidResourceType(resourceType)) {
139 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
140 "Unexpected resource type " + resourceType, null);
141 }else if (!DATA_VALIDATOR.isValid(new SecureString(resourceType))){
142 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
143 "Unsafe resource type " + resourceType, null);
145 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
146 searchService.getWidgetData(resourceType));
151 * Saves a batch of events, news or resources.
153 * @param commonWidgetMeta
154 * read from POST body.
155 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
157 @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
158 public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
159 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
160 if (!DATA_VALIDATOR.isValid(commonWidgetMeta)){
161 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
162 "Unsafe resource type " + commonWidgetMeta, "ERROR");
163 }else if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) {
164 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
165 "Category cannot be null or empty");
166 }else if (!isValidResourceType(commonWidgetMeta.getCategory())) {
167 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
168 "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
170 for (CommonWidget cw : commonWidgetMeta.getItems()) {
171 String err = validateCommonWidget(cw);
173 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
175 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
176 searchService.saveWidgetDataBulk(commonWidgetMeta));
180 * Saves one: event, news or resource
182 * @param commonWidget
183 * read from POST body
184 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
186 @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
187 public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget, HttpServletRequest request, HttpServletResponse response) {
188 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
189 EPUser user = EPUserUtils.getUserSession(request);
190 if (adminRolesService.isSuperAdmin(user)) {
191 if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().isEmpty()) {
192 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
193 "Category cannot be null or empty");
194 }else if (!DATA_VALIDATOR.isValid(commonWidget)){
195 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
196 "Unsafe resource type " + commonWidget, "ERROR");
198 String err = validateCommonWidget(commonWidget);
200 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
201 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
202 searchService.saveWidgetData(commonWidget));
204 EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
205 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed", null);
210 * Used by the validate function
212 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
215 * Validates the content of a common widget.
218 * @return null on success; an error message if validation fails.
221 private String validateCommonWidget(CommonWidget cw) {
222 if (!isValidResourceType(cw.getCategory()))
223 return "Invalid category: " + cw.getCategory();
224 if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
225 return "Title is missing";
226 if (cw.getHref() == null || cw.getHref().trim().length() == 0)
227 return "HREF is missing";
228 if (!cw.getHref().toLowerCase().startsWith("http"))
229 return "HREF does not start with http";
230 if (cw.getSortOrder() == null)
231 return "Sort order is null";
232 if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
233 return "Date is missing";
235 yearMonthDayFormat.setLenient(false);
236 Date date = yearMonthDayFormat.parse(cw.getEventDate());
238 return "Failed to parse date " + cw.getEventDate();
239 } catch (ParseException ex) {
240 return "Invalid date format " +ex.toString();
246 * Deletes one: event, news or resource
248 * @param commonWidget
249 * read from POST body
250 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
252 @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
253 public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
254 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
255 if (!DATA_VALIDATOR.isValid(commonWidget)){
256 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
257 "Unsafe resource type " + commonWidget, "ERROR");
259 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
260 searchService.deleteWidgetData(commonWidget));
264 * Searches all portal for the input string.
267 * @param searchString
268 * @return Rest response wrapped around a Map of String to List of Search
272 @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
273 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
274 @RequestParam String searchString) {
275 if (!DATA_VALIDATOR.isValid(new SecureString(searchString))){
276 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not safe",
279 if (searchString != null)
280 searchString = searchString.trim();
281 EPUser user = EPUserUtils.getUserSession(request);
284 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
285 "searchPortal: User object is null? - check logs",
287 } else if (searchString == null || searchString.length() == 0) {
288 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
291 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
292 user.getLoginId(), searchString);
293 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
295 /*Audit log the search*/
296 AuditLog auditLog = new AuditLog();
297 auditLog.setUserId(user.getId());
298 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
299 auditLog.setComments(EcompPortalUtils.truncateString(searchString, PortalConstants.AUDIT_LOG_COMMENT_SIZE));
300 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
301 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE);
302 MDC.put(com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
303 auditService.logActivity(auditLog, null);
304 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
306 MDC.put(EPCommonSystemProperties.STATUS_CODE, "COMPLETE");
307 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
308 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse",
309 EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));
310 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
311 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
312 MDC.remove(SystemProperties.MDC_TIMER);
313 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
314 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
316 } catch (Exception e) {
317 logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
318 MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
319 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
320 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
326 * Gets all active users.
328 * TODO: should only the superuser be allowed to use this API?
331 * @return Rest response wrapped around a list of String
333 @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
334 public List<String> getActiveUsers(HttpServletRequest request) {
335 List<String> activeUsers;
336 List<String> onlineUsers = new ArrayList<>();
338 EPUser user = EPUserUtils.getUserSession(request);
339 String userId = user.getOrgUserId();
341 activeUsers = searchService.getRelatedUsers(userId);
342 HashSet<String> usersSet = (HashSet<String>) CollaborateList.getInstance().getAllUserName();
343 for (String users : activeUsers) {
344 if (usersSet.contains(users)) {
345 onlineUsers.add(users);
349 } catch (Exception e) {
350 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
356 * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
359 * @return Rest response wrapped around a number that is the number of milliseconds.
361 @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
362 public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
364 String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);
365 String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);
366 Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
367 Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
368 Map<String, String> results = new HashMap<>();
369 results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
370 results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
371 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
372 } catch (Exception e) {
373 logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
374 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
379 * Gets the window width threshold for collapsing right menu from system.properties.
382 * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
384 @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
385 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
387 String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
388 Integer windowWidth = Integer.valueOf(windowWidthString);
389 Map<String, String> results = new HashMap<>();
390 results.put("windowWidth", String.valueOf(windowWidth));
391 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
392 } catch (Exception e) {
393 logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
394 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
400 * Gets the window width threshold for collapsing left menu from system.properties.
403 * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
405 @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
406 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
408 String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
409 Integer windowWidth = Integer.valueOf(windowWidthString);
410 Map<String, String> results = new HashMap<>();
411 results.put("windowWidth", String.valueOf(windowWidth));
412 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
413 } catch (Exception e) {
414 logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
415 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
420 * Gets only those users that are 'related' to the currently logged-in user.
423 * @return Rest response wrapped around a List of String
425 @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
426 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
427 EPUser user = EPUserUtils.getUserSession(request);
430 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
433 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
434 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
435 searchService.getRelatedUsers(user.getLoginId()));
437 } catch (Exception e) {
438 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
439 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",