removed code smells
[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.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;
76 import org.slf4j.MDC;
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;
85
86 /**
87  * Controller supplies data to Angular services on the dashboard page.
88  */
89 @Configuration
90 @RestController
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);
95
96         private DashboardSearchService searchService;
97         private AuditService auditService;
98         private AdminRolesService adminRolesService;
99
100         @Autowired
101         public DashboardController(DashboardSearchService searchService,
102                 AuditService auditService, AdminRolesService adminRolesService) {
103                 this.searchService = searchService;
104                 this.auditService = auditService;
105                 this.adminRolesService = adminRolesService;
106         }
107
108         public enum WidgetCategory {
109                 EVENTS, NEWS, IMPORTANTRESOURCES
110         }
111
112         /**
113          * Validates the resource type parameter.
114          * 
115          * @param resourceType
116          * @return True if known in the enum WidgetCategory, else false.
117          */
118         private boolean isValidResourceType(String resourceType) {
119                 if (resourceType == null)
120                         return false;
121                 for (WidgetCategory wc : WidgetCategory.values())
122                         if (wc.name().equals(resourceType))
123                                 return true;
124                 return false;
125         }
126
127         /**
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)
130          * 
131          * @param request
132          * @param resourceType
133          *            Request parameter.
134          * @return Rest response wrapped around a CommonWidgetMeta object.
135          */
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);
145                 }
146                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
147                         searchService.getWidgetData(resourceType));
148         }
149         
150         
151         /**
152          * Saves a batch of events, news or resources.
153          * 
154          * @param commonWidgetMeta
155          *            read from POST body.
156          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
157          */
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);
170                 }
171                 for (CommonWidget cw : commonWidgetMeta.getItems()) {
172                         String err = validateCommonWidget(cw);
173                         if (err != null)
174                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
175                 }
176                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
177                         searchService.saveWidgetDataBulk(commonWidgetMeta));
178         }
179
180         /**
181          * Saves one: event, news or resource
182          * 
183          * @param commonWidget
184          *            read from POST body
185          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
186          */
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");
198                         }
199                         String err = validateCommonWidget(commonWidget);
200                         if (err != null)
201                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
202                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
203                                 searchService.saveWidgetData(commonWidget));
204                 } else {
205                         EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
206                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed", null);
207                 }
208         }
209
210         /**
211          * Used by the validate function
212          */
213         private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
214
215         /**
216          * Validates the content of a common widget.
217          * 
218          * @param cw
219          * @return null on success; an error message if validation fails.
220          * @throws Exception
221          */
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";
235                 try {
236                         yearMonthDayFormat.setLenient(false);
237                         Date date = yearMonthDayFormat.parse(cw.getEventDate());
238                         if (date == null)
239                                 return "Failed to parse date " + cw.getEventDate();
240                 } catch (ParseException ex) {
241                         return "Invalid date format " +ex.toString();
242                 }
243                 return null;
244         }
245
246         /**
247          * Deletes one: event, news or resource
248          * 
249          * @param commonWidget
250          *            read from POST body
251          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
252          */
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");
259                 }
260                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
261                         searchService.deleteWidgetData(commonWidget));
262         }
263
264         /**
265          * Searches all portal for the input string.
266          * 
267          * @param request
268          * @param searchString
269          * @return Rest response wrapped around a Map of String to List of Search
270          *         Result Item.
271          */
272         @EPAuditLog
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",
278                                 new HashMap<>());
279                 }
280                 if (searchString != null)
281                         searchString = searchString.trim();
282                 EPUser user = EPUserUtils.getUserSession(request);
283                 try {
284                         if (user == null) {
285                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
286                                                 "searchPortal: User object is null? - check logs",
287                                         new HashMap<>());
288                         } else if (searchString == null || searchString.length() == 0) {
289                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
290                                         new HashMap<>());
291                         } else {
292                                 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
293                                                 user.getLoginId(), searchString);
294                                 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
295                                                 searchString);
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());
306                                 
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);
316                         }
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.",
322                                 new HashMap<>());
323                 }
324         }
325
326         /**
327          * Gets all active users.
328          * 
329          * TODO: should only the superuser be allowed to use this API?
330          * 
331          * @param request
332          * @return Rest response wrapped around a list of String
333          */
334         @GetMapping(value = "/activeUsers", produces = "application/json")
335         public List<String> getActiveUsers(HttpServletRequest request) {
336                 List<String> activeUsers;
337                 List<String> onlineUsers = new ArrayList<>();
338                 try {
339                         EPUser user = EPUserUtils.getUserSession(request);
340                         String userId = user.getOrgUserId();
341
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);
347                                 }
348                         }
349
350                 } catch (Exception e) {
351                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
352                 }
353                 return onlineUsers;
354         }
355         
356         /**
357          * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
358          * 
359          * @param request
360          * @return Rest response wrapped around a number that is the number of milliseconds.
361          */
362         @GetMapping(value = "/onlineUserUpdateRate", produces = "application/json")
363         public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
364                 try {
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);
376                 }               
377         }
378
379         /**
380          * Gets the window width threshold for collapsing right menu from system.properties.
381          * 
382          * @param request
383          * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
384          */
385         @GetMapping(value = "/windowWidthThresholdRightMenu", produces = "application/json")
386         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
387                 try {
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);
396                 }               
397         }
398
399
400         /**
401          * Gets the window width threshold for collapsing left menu from system.properties.
402          * 
403          * @param request
404          * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
405          */
406         @GetMapping(value = "/windowWidthThresholdLeftMenu", produces = "application/json")
407         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
408                 try {
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);
417                 }               
418         }
419         
420         /**
421          * Gets only those users that are 'related' to the currently logged-in user.
422          * 
423          * @param request
424          * @return Rest response wrapped around a List of String
425          */
426         @GetMapping(value = "/relatedUsers", produces = "application/json")
427         public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
428                 EPUser user = EPUserUtils.getUserSession(request);
429                 try {
430                         if (user == null) {
431                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
432                                                 new ArrayList<>());
433                         } else {
434                                 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
435                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
436                                                 searchService.getRelatedUsers(user.getLoginId()));
437                         }
438                 } catch (Exception e) {
439                         logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
440                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
441                                         new ArrayList<>());
442                 }
443         }
444
445 }