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.PutMapping;
84 import org.springframework.web.bind.annotation.DeleteMapping;
85 import org.springframework.web.bind.annotation.RequestMethod;
86 import org.springframework.web.bind.annotation.RequestParam;
87 import org.springframework.web.bind.annotation.RestController;
90 * Controller supplies data to Angular services on the dashboard page.
94 @RequestMapping("/portalApi/dashboard")
95 public class DashboardController extends EPRestrictedBaseController {
96 private static final DataValidator DATA_VALIDATOR = new DataValidator();
97 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
99 private DashboardSearchService searchService;
100 private AuditService auditService;
101 private AdminRolesService adminRolesService;
104 public DashboardController(DashboardSearchService searchService,
105 AuditService auditService, AdminRolesService adminRolesService) {
106 this.searchService = searchService;
107 this.auditService = auditService;
108 this.adminRolesService = adminRolesService;
111 public enum WidgetCategory {
112 EVENTS, NEWS, IMPORTANTRESOURCES
116 * Validates the resource type parameter.
118 * @param resourceType
119 * @return True if known in the enum WidgetCategory, else false.
121 private boolean isValidResourceType(String resourceType) {
122 if (resourceType == null)
124 for (WidgetCategory wc : WidgetCategory.values())
125 if (wc.name().equals(resourceType))
131 * Gets all widgets of the specified resource type.
132 * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
135 * @param resourceType
137 * @return Rest response wrapped around a CommonWidgetMeta object.
139 @GetMapping(value = "/widgetData", produces = "application/json")
140 public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
141 @RequestParam String resourceType) {
142 if (!isValidResourceType(resourceType)) {
143 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
144 "Unexpected resource type " + resourceType, null);
145 }else if (!DATA_VALIDATOR.isValid(new SecureString(resourceType))){
146 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
147 "Unsafe resource type " + resourceType, null);
149 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
150 searchService.getWidgetData(resourceType));
155 * Saves a batch of events, news or resources.
157 * @param commonWidgetMeta
158 * read from POST body.
159 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
161 @PostMapping(value = "/widgetDataBulk", produces = "application/json")
162 public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
163 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
164 if (!DATA_VALIDATOR.isValid(commonWidgetMeta)){
165 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
166 "Unsafe resource type " + commonWidgetMeta, "ERROR");
167 }else if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) {
168 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
169 "Category cannot be null or empty");
170 }else if (!isValidResourceType(commonWidgetMeta.getCategory())) {
171 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
172 "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
174 for (CommonWidget cw : commonWidgetMeta.getItems()) {
175 String err = validateCommonWidget(cw);
177 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
179 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
180 searchService.saveWidgetDataBulk(commonWidgetMeta));
184 * Saves one: event, news or resource
186 * @param commonWidget
187 * read from POST body
188 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
190 @PostMapping(value = "/widgetData", produces = "application/json")
191 public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget, HttpServletRequest request, HttpServletResponse response) {
192 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
193 EPUser user = EPUserUtils.getUserSession(request);
194 if (adminRolesService.isSuperAdmin(user)) {
195 if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().isEmpty()) {
196 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
197 "Category cannot be null or empty");
198 }else if (!DATA_VALIDATOR.isValid(commonWidget)){
199 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
200 "Unsafe resource type " + commonWidget, "ERROR");
202 String err = validateCommonWidget(commonWidget);
204 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
205 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
206 searchService.saveWidgetData(commonWidget));
208 EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
209 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed", null);
214 * Used by the validate function
216 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
219 * Validates the content of a common widget.
222 * @return null on success; an error message if validation fails.
225 private String validateCommonWidget(CommonWidget cw) {
226 if (!isValidResourceType(cw.getCategory()))
227 return "Invalid category: " + cw.getCategory();
228 if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
229 return "Title is missing";
230 if (cw.getHref() == null || cw.getHref().trim().length() == 0)
231 return "HREF is missing";
232 if (!cw.getHref().toLowerCase().startsWith("http"))
233 return "HREF does not start with http";
234 if (cw.getSortOrder() == null)
235 return "Sort order is null";
236 if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
237 return "Date is missing";
239 yearMonthDayFormat.setLenient(false);
240 Date date = yearMonthDayFormat.parse(cw.getEventDate());
242 return "Failed to parse date " + cw.getEventDate();
243 } catch (ParseException ex) {
244 return "Invalid date format " +ex.toString();
250 * Deletes one: event, news or resource
252 * @param commonWidget
253 * read from POST body
254 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
256 @PostMapping(value = "/deleteData", produces = "application/json")
257 public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
258 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
259 if (!DATA_VALIDATOR.isValid(commonWidget)){
260 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
261 "Unsafe resource type " + commonWidget, "ERROR");
263 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
264 searchService.deleteWidgetData(commonWidget));
268 * Searches all portal for the input string.
271 * @param searchString
272 * @return Rest response wrapped around a Map of String to List of Search
276 @GetMapping(value = "/search", produces = "application/json")
277 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
278 @RequestParam String searchString) {
279 if (!DATA_VALIDATOR.isValid(new SecureString(searchString))){
280 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not safe",
283 if (searchString != null)
284 searchString = searchString.trim();
285 EPUser user = EPUserUtils.getUserSession(request);
288 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
289 "searchPortal: User object is null? - check logs",
291 } else if (searchString == null || searchString.length() == 0) {
292 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
295 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
296 user.getLoginId(), searchString);
297 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
299 /*Audit log the search*/
300 AuditLog auditLog = new AuditLog();
301 auditLog.setUserId(user.getId());
302 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
303 auditLog.setComments(EcompPortalUtils.truncateString(searchString, PortalConstants.AUDIT_LOG_COMMENT_SIZE));
304 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
305 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE);
306 MDC.put(com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
307 auditService.logActivity(auditLog, null);
308 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
310 MDC.put(EPCommonSystemProperties.STATUS_CODE, "COMPLETE");
311 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
312 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse",
313 EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));
314 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
315 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
316 MDC.remove(SystemProperties.MDC_TIMER);
317 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
318 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
320 } catch (Exception e) {
321 logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
322 MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
323 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
324 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
330 * Gets all active users.
332 * TODO: should only the superuser be allowed to use this API?
335 * @return Rest response wrapped around a list of String
337 @GetMapping(value = "/activeUsers", produces = "application/json")
338 public List<String> getActiveUsers(HttpServletRequest request) {
339 List<String> activeUsers;
340 List<String> onlineUsers = new ArrayList<>();
342 EPUser user = EPUserUtils.getUserSession(request);
343 String userId = user.getOrgUserId();
345 activeUsers = searchService.getRelatedUsers(userId);
346 HashSet<String> usersSet = (HashSet<String>) CollaborateList.getInstance().getAllUserName();
347 for (String users : activeUsers) {
348 if (usersSet.contains(users)) {
349 onlineUsers.add(users);
353 } catch (Exception e) {
354 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
360 * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
363 * @return Rest response wrapped around a number that is the number of milliseconds.
365 @GetMapping(value = "/onlineUserUpdateRate", produces = "application/json")
366 public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
368 String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);
369 String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);
370 Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
371 Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
372 Map<String, String> results = new HashMap<>();
373 results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
374 results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
375 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
376 } catch (Exception e) {
377 logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
378 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
383 * Gets the window width threshold for collapsing right menu from system.properties.
386 * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
388 @GetMapping(value = "/windowWidthThresholdRightMenu", produces = "application/json")
389 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
391 String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
392 Integer windowWidth = Integer.valueOf(windowWidthString);
393 Map<String, String> results = new HashMap<>();
394 results.put("windowWidth", String.valueOf(windowWidth));
395 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
396 } catch (Exception e) {
397 logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
398 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
404 * Gets the window width threshold for collapsing left menu from system.properties.
407 * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
409 @GetMapping(value = "/windowWidthThresholdLeftMenu", produces = "application/json")
410 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
412 String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
413 Integer windowWidth = Integer.valueOf(windowWidthString);
414 Map<String, String> results = new HashMap<>();
415 results.put("windowWidth", String.valueOf(windowWidth));
416 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
417 } catch (Exception e) {
418 logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
419 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
424 * Gets only those users that are 'related' to the currently logged-in user.
427 * @return Rest response wrapped around a List of String
429 @GetMapping(value = "/relatedUsers", produces = "application/json")
430 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
431 EPUser user = EPUserUtils.getUserSession(request);
434 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
437 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
438 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
439 searchService.getRelatedUsers(user.getLoginId()));
441 } catch (Exception e) {
442 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
443 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",