Replace ecomp references
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / DashboardController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
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
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
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
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
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.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.controller;
39
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;
47 import java.util.Map;
48
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
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;
74 import org.slf4j.MDC;
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;
82
83 /**
84  * Controller supplies data to Angular services on the dashboard page.
85  */
86 @Configuration
87 @RestController
88 @RequestMapping("/portalApi/dashboard")
89 public class DashboardController extends EPRestrictedBaseController {
90
91         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
92
93         @Autowired
94         private DashboardSearchService searchService;
95         @Autowired
96         private AuditService auditService;
97         
98         @Autowired
99         private AdminRolesService adminRolesService;
100         
101         public enum WidgetCategory {
102                 EVENTS, NEWS, IMPORTANTRESOURCES;
103         }
104
105         /**
106          * Validates the resource type parameter.
107          * 
108          * @param resourceType
109          * @return True if known in the enum WidgetCategory, else false.
110          */
111         private boolean isValidResourceType(String resourceType) {
112                 if (resourceType == null)
113                         return false;
114                 for (WidgetCategory wc : WidgetCategory.values())
115                         if (wc.name().equals(resourceType))
116                                 return true;
117                 return false;
118         }
119
120         /**
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)
123          * 
124          * @param request
125          * @param resourceType
126          *            Request parameter.
127          * @return Rest response wrapped around a CommonWidgetMeta object.
128          */
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));
137         }
138         
139         
140         /**
141          * Saves a batch of events, news or resources.
142          * 
143          * @param commonWidgetMeta
144          *            read from POST body.
145          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
146          */
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);
156                 // validate dates
157                 for (CommonWidget cw : commonWidgetMeta.getItems()) {
158                         String err = validateCommonWidget(cw);
159                         if (err != null)
160                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
161                 }
162                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
163                                 searchService.saveWidgetDataBulk(commonWidgetMeta));
164         }
165
166         /**
167          * Saves one: event, news or resource
168          * 
169          * @param commonWidget
170          *            read from POST body
171          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
172          */
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);
182                         if (err != null)
183                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
184                         return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
185                                         searchService.saveWidgetData(commonWidget));
186                 } else {
187                         EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
188                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed", null);
189                 }
190         }
191
192         /**
193          * Used by the validate function
194          */
195         private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
196
197         /**
198          * Validates the content of a common widget.
199          * 
200          * @param cw
201          * @return null on success; an error message if validation fails.
202          * @throws Exception
203          */
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";
217                 try {
218                         yearMonthDayFormat.setLenient(false);
219                         Date date = yearMonthDayFormat.parse(cw.getEventDate());
220                         if (date == null)
221                                 return "Failed to parse date " + cw.getEventDate();
222                 } catch (ParseException ex) {
223                         return "Invalid date format " +ex.toString();
224                 }
225                 return null;
226         }
227
228         /**
229          * Deletes one: event, news or resource
230          * 
231          * @param commonWidget
232          *            read from POST body
233          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
234          */
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));
240         }
241
242         /**
243          * Searches all portal for the input string.
244          * 
245          * @param request
246          * @param searchString
247          * @return Rest response wrapped around a Map of String to List of Search
248          *         Result Item.
249          */
250         @EPAuditLog
251         @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
252         public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
253                         @RequestParam String searchString) {
254
255                 if (searchString != null)
256                         searchString = searchString.trim();
257                 EPUser user = EPUserUtils.getUserSession(request);
258                 try {
259                         if (user == null) {
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>>());
266                         } else {
267                                 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
268                                                 user.getLoginId(), searchString);
269                                 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
270                                                 searchString);
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());
281                                 
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);
291                         }
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>>());
298                 }
299         }
300
301         /**
302          * Gets all active users.
303          * 
304          * TODO: should only the superuser be allowed to use this API?
305          * 
306          * @param request
307          * @return Rest response wrapped around a list of String
308          */
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<>();
313                 try {
314                         EPUser user = EPUserUtils.getUserSession(request);
315                         String userId = user.getOrgUserId();
316
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);
322                                 }
323                         }
324
325                 } catch (Exception e) {
326                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
327                 }
328                 return onlineUsers;
329         }
330         
331         /**
332          * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
333          * 
334          * @param request
335          * @return Rest response wrapped around a number that is the number of milliseconds.
336          */
337         @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
338         public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
339                 try {
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);
351                 }               
352         }
353
354         /**
355          * Gets the window width threshold for collapsing right menu from system.properties.
356          * 
357          * @param request
358          * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
359          */
360         @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
361         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
362                 try {
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);
371                 }               
372         }
373
374
375         /**
376          * Gets the window width threshold for collapsing left menu from system.properties.
377          * 
378          * @param request
379          * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
380          */
381         @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
382         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
383                 try {
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);
392                 }               
393         }
394         
395         /**
396          * Gets only those users that are 'related' to the currently logged-in user.
397          * 
398          * @param request
399          * @return Rest response wrapped around a List of String
400          */
401         @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
402         public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
403                 EPUser user = EPUserUtils.getUserSession(request);
404                 try {
405                         if (user == null) {
406                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
407                                                 new ArrayList<>());
408                         } else {
409                                 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
410                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
411                                                 searchService.getRelatedUsers(user.getLoginId()));
412                         }
413                 } catch (Exception e) {
414                         logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
415                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
416                                         new ArrayList<>());
417                 }
418         }
419
420 }