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.GetMapping;
82 import org.springframework.web.bind.annotation.PostMapping;
83 import org.springframework.web.bind.annotation.RequestParam;
84 import org.springframework.web.bind.annotation.RestController;
87 * Controller supplies data to Angular services on the dashboard page.
91 @RequestMapping("/portalApi/dashboard")
92 public class DashboardController extends EPRestrictedBaseController {
93 private static final DataValidator DATA_VALIDATOR = new DataValidator();
94 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
96 private DashboardSearchService searchService;
97 private AuditService auditService;
98 private AdminRolesService adminRolesService;
101 public DashboardController(DashboardSearchService searchService,
102 AuditService auditService, AdminRolesService adminRolesService) {
103 this.searchService = searchService;
104 this.auditService = auditService;
105 this.adminRolesService = adminRolesService;
108 public enum WidgetCategory {
109 EVENTS, NEWS, IMPORTANTRESOURCES
113 * Validates the resource type parameter.
115 * @param resourceType
116 * @return True if known in the enum WidgetCategory, else false.
118 private boolean isValidResourceType(String resourceType) {
119 if (resourceType == null)
121 for (WidgetCategory wc : WidgetCategory.values())
122 if (wc.name().equals(resourceType))
128 * Gets all widgets of the specified resource type.
129 * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
132 * @param resourceType
134 * @return Rest response wrapped around a CommonWidgetMeta object.
136 @GetMapping(value = "/widgetData", produces = "application/json")
137 public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
138 @RequestParam String resourceType) {
139 if (!isValidResourceType(resourceType)) {
140 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
141 "Unexpected resource type " + resourceType, null);
142 }else if (!DATA_VALIDATOR.isValid(new SecureString(resourceType))){
143 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
144 "Unsafe resource type " + resourceType, null);
146 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
147 searchService.getWidgetData(resourceType));
152 * Saves a batch of events, news or resources.
154 * @param commonWidgetMeta
155 * read from POST body.
156 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
158 @PostMapping(value = "/widgetDataBulk", produces = "application/json")
159 public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
160 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
161 if (!DATA_VALIDATOR.isValid(commonWidgetMeta)){
162 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
163 "Unsafe resource type " + commonWidgetMeta, "ERROR");
164 }else if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) {
165 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
166 "Category cannot be null or empty");
167 }else if (!isValidResourceType(commonWidgetMeta.getCategory())) {
168 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
169 "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
171 for (CommonWidget cw : commonWidgetMeta.getItems()) {
172 String err = validateCommonWidget(cw);
174 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
176 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
177 searchService.saveWidgetDataBulk(commonWidgetMeta));
181 * Saves one: event, news or resource
183 * @param commonWidget
184 * read from POST body
185 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
187 @PostMapping(value = "/widgetData", produces = "application/json")
188 public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget, HttpServletRequest request, HttpServletResponse response) {
189 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
190 EPUser user = EPUserUtils.getUserSession(request);
191 if (adminRolesService.isSuperAdmin(user)) {
192 if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().isEmpty()) {
193 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
194 "Category cannot be null or empty");
195 }else if (!DATA_VALIDATOR.isValid(commonWidget)){
196 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
197 "Unsafe resource type " + commonWidget, "ERROR");
199 String err = validateCommonWidget(commonWidget);
201 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
202 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
203 searchService.saveWidgetData(commonWidget));
205 EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
206 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed", null);
211 * Used by the validate function
213 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
216 * Validates the content of a common widget.
219 * @return null on success; an error message if validation fails.
222 private String validateCommonWidget(CommonWidget cw) {
223 if (!isValidResourceType(cw.getCategory()))
224 return "Invalid category: " + cw.getCategory();
225 if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
226 return "Title is missing";
227 if (cw.getHref() == null || cw.getHref().trim().length() == 0)
228 return "HREF is missing";
229 if (!cw.getHref().toLowerCase().startsWith("http"))
230 return "HREF does not start with http";
231 if (cw.getSortOrder() == null)
232 return "Sort order is null";
233 if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
234 return "Date is missing";
236 yearMonthDayFormat.setLenient(false);
237 Date date = yearMonthDayFormat.parse(cw.getEventDate());
239 return "Failed to parse date " + cw.getEventDate();
240 } catch (ParseException ex) {
241 return "Invalid date format " +ex.toString();
247 * Deletes one: event, news or resource
249 * @param commonWidget
250 * read from POST body
251 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
253 @PostMapping(value = "/deleteData", produces = "application/json")
254 public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
255 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
256 if (!DATA_VALIDATOR.isValid(commonWidget)){
257 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
258 "Unsafe resource type " + commonWidget, "ERROR");
260 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
261 searchService.deleteWidgetData(commonWidget));
265 * Searches all portal for the input string.
268 * @param searchString
269 * @return Rest response wrapped around a Map of String to List of Search
273 @GetMapping(value = "/search", produces = "application/json")
274 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
275 @RequestParam String searchString) {
276 if (!DATA_VALIDATOR.isValid(new SecureString(searchString))){
277 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not safe",
280 if (searchString != null)
281 searchString = searchString.trim();
282 EPUser user = EPUserUtils.getUserSession(request);
285 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
286 "searchPortal: User object is null? - check logs",
288 } else if (searchString == null || searchString.length() == 0) {
289 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
292 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
293 user.getLoginId(), searchString);
294 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
296 /*Audit log the search*/
297 AuditLog auditLog = new AuditLog();
298 auditLog.setUserId(user.getId());
299 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
300 auditLog.setComments(EcompPortalUtils.truncateString(searchString, PortalConstants.AUDIT_LOG_COMMENT_SIZE));
301 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
302 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE);
303 MDC.put(com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
304 auditService.logActivity(auditLog, null);
305 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
307 MDC.put(EPCommonSystemProperties.STATUS_CODE, "COMPLETE");
308 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
309 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse",
310 EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));
311 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
312 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
313 MDC.remove(SystemProperties.MDC_TIMER);
314 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
315 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
317 } catch (Exception e) {
318 logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
319 MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
320 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
321 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
327 * Gets all active users.
329 * TODO: should only the superuser be allowed to use this API?
332 * @return Rest response wrapped around a list of String
334 @GetMapping(value = "/activeUsers", produces = "application/json")
335 public List<String> getActiveUsers(HttpServletRequest request) {
336 List<String> activeUsers;
337 List<String> onlineUsers = new ArrayList<>();
339 EPUser user = EPUserUtils.getUserSession(request);
340 String userId = user.getOrgUserId();
342 activeUsers = searchService.getRelatedUsers(userId);
343 HashSet<String> usersSet = (HashSet<String>) CollaborateList.getInstance().getAllUserName();
344 for (String users : activeUsers) {
345 if (usersSet.contains(users)) {
346 onlineUsers.add(users);
350 } catch (Exception e) {
351 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
357 * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
360 * @return Rest response wrapped around a number that is the number of milliseconds.
362 @GetMapping(value = "/onlineUserUpdateRate", produces = "application/json")
363 public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
365 String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);
366 String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);
367 Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
368 Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
369 Map<String, String> results = new HashMap<>();
370 results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
371 results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
372 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
373 } catch (Exception e) {
374 logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
375 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
380 * Gets the window width threshold for collapsing right menu from system.properties.
383 * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
385 @GetMapping(value = "/windowWidthThresholdRightMenu", produces = "application/json")
386 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
388 String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
389 Integer windowWidth = Integer.valueOf(windowWidthString);
390 Map<String, String> results = new HashMap<>();
391 results.put("windowWidth", String.valueOf(windowWidth));
392 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
393 } catch (Exception e) {
394 logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
395 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
401 * Gets the window width threshold for collapsing left menu from system.properties.
404 * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
406 @GetMapping(value = "/windowWidthThresholdLeftMenu", produces = "application/json")
407 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
409 String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
410 Integer windowWidth = Integer.valueOf(windowWidthString);
411 Map<String, String> results = new HashMap<>();
412 results.put("windowWidth", String.valueOf(windowWidth));
413 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
414 } catch (Exception e) {
415 logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
416 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
421 * Gets only those users that are 'related' to the currently logged-in user.
424 * @return Rest response wrapped around a List of String
426 @GetMapping(value = "/relatedUsers", produces = "application/json")
427 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
428 EPUser user = EPUserUtils.getUserSession(request);
431 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
434 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
435 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
436 searchService.getRelatedUsers(user.getLoginId()));
438 } catch (Exception e) {
439 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
440 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",