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.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, HttpServletResponse response) {
175 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
176 EPUser user = EPUserUtils.getUserSession(request);
177 if (adminRolesService.isSuperAdmin(user)) {
178 if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().isEmpty())
179 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
180 "Category cannot be null or empty");
181 String err = validateCommonWidget(commonWidget);
183 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
184 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
185 searchService.saveWidgetData(commonWidget));
187 EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
188 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed", null);
193 * Used by the validate function
195 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
198 * Validates the content of a common widget.
201 * @return null on success; an error message if validation fails.
204 private String validateCommonWidget(CommonWidget cw) {
205 if (!isValidResourceType(cw.getCategory()))
206 return "Invalid category: " + cw.getCategory();
207 if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
208 return "Title is missing";
209 if (cw.getHref() == null || cw.getHref().trim().length() == 0)
210 return "HREF is missing";
211 if (!cw.getHref().toLowerCase().startsWith("http"))
212 return "HREF does not start with http";
213 if (cw.getSortOrder() == null)
214 return "Sort order is null";
215 if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
216 return "Date is missing";
218 yearMonthDayFormat.setLenient(false);
219 Date date = yearMonthDayFormat.parse(cw.getEventDate());
221 return "Failed to parse date " + cw.getEventDate();
222 } catch (ParseException ex) {
223 return "Invalid date format " +ex.toString();
229 * Deletes one: event, news or resource
231 * @param commonWidget
232 * read from POST body
233 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
235 @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
236 public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
237 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
238 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
239 searchService.deleteWidgetData(commonWidget));
243 * Searches all portal for the input string.
246 * @param searchString
247 * @return Rest response wrapped around a Map of String to List of Search
251 @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
252 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
253 @RequestParam String searchString) {
255 if (searchString != null)
256 searchString = searchString.trim();
257 EPUser user = EPUserUtils.getUserSession(request);
260 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
261 "searchPortal: User object is null? - check logs",
262 new HashMap<String, List<SearchResultItem>>());
263 } else if (searchString == null || searchString.length() == 0) {
264 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
265 new HashMap<String, List<SearchResultItem>>());
267 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
268 user.getLoginId(), searchString);
269 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
271 /*Audit log the search*/
272 AuditLog auditLog = new AuditLog();
273 auditLog.setUserId(user.getId());
274 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
275 auditLog.setComments(EcompPortalUtils.truncateString(searchString, PortalConstants.AUDIT_LOG_COMMENT_SIZE));
276 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
277 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE);
278 MDC.put(com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
279 auditService.logActivity(auditLog, null);
280 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
282 MDC.put(EPCommonSystemProperties.STATUS_CODE, "COMPLETE");
283 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
284 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse",
285 EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));
286 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
287 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
288 MDC.remove(SystemProperties.MDC_TIMER);
289 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
290 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
292 } catch (Exception e) {
293 logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
294 MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
295 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
296 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
297 new HashMap<String, List<SearchResultItem>>());
302 * Gets all active users.
304 * TODO: should only the superuser be allowed to use this API?
307 * @return Rest response wrapped around a list of String
309 @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
310 public List<String> getActiveUsers(HttpServletRequest request) {
311 List<String> activeUsers = null;
312 List<String> onlineUsers = new ArrayList<>();
314 EPUser user = EPUserUtils.getUserSession(request);
315 String userId = user.getOrgUserId();
317 activeUsers = searchService.getRelatedUsers(userId);
318 HashSet<String> usersSet = (HashSet<String>) CollaborateList.getInstance().getAllUserName();
319 for (String users : activeUsers) {
320 if (usersSet.contains(users)) {
321 onlineUsers.add(users);
325 } catch (Exception e) {
326 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
332 * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
335 * @return Rest response wrapped around a number that is the number of milliseconds.
337 @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
338 public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
340 String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);
341 String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);
342 Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
343 Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
344 Map<String, String> results = new HashMap<String,String>();
345 results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
346 results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
347 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
348 } catch (Exception e) {
349 logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
350 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
355 * Gets the window width threshold for collapsing right menu from system.properties.
358 * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
360 @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
361 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
363 String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
364 Integer windowWidth = Integer.valueOf(windowWidthString);
365 Map<String, String> results = new HashMap<String,String>();
366 results.put("windowWidth", String.valueOf(windowWidth));
367 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
368 } catch (Exception e) {
369 logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
370 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
376 * Gets the window width threshold for collapsing left menu from system.properties.
379 * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
381 @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
382 public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
384 String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
385 Integer windowWidth = Integer.valueOf(windowWidthString);
386 Map<String, String> results = new HashMap<String,String>();
387 results.put("windowWidth", String.valueOf(windowWidth));
388 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
389 } catch (Exception e) {
390 logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
391 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
396 * Gets only those users that are 'related' to the currently logged-in user.
399 * @return Rest response wrapped around a List of String
401 @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
402 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
403 EPUser user = EPUserUtils.getUserSession(request);
406 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
409 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
410 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
411 searchService.getRelatedUsers(user.getLoginId()));
413 } catch (Exception e) {
414 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
415 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",