nexus site path corrected
[portal.git] / ecomp-portal-BE / src / main / java / org / openecomp / portalapp / portal / controller / DashboardController.java
1 /*-
2  * ================================================================================
3  * eCOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.controller;
21
22 import java.text.ParseException;
23 import java.text.SimpleDateFormat;
24 import java.util.ArrayList;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.servlet.http.HttpServletRequest;
32
33 import org.openecomp.portalapp.controller.EPRestrictedBaseController;
34 import org.openecomp.portalapp.portal.domain.EPUser;
35 import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
36 import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
37 import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
38 import org.openecomp.portalapp.portal.service.DashboardSearchService;
39 import org.openecomp.portalapp.portal.transport.CommonWidget;
40 import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
41 import org.openecomp.portalapp.portal.utils.EPSystemProperties;
42 import org.openecomp.portalapp.util.EPUserUtils;
43 import org.openecomp.portalsdk.core.domain.support.CollaborateList;
44 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
45 import org.openecomp.portalsdk.core.util.SystemProperties;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.web.bind.annotation.RequestBody;
48 import org.springframework.web.bind.annotation.RequestMapping;
49 import org.springframework.web.bind.annotation.RequestMethod;
50 import org.springframework.web.bind.annotation.RequestParam;
51 import org.springframework.web.bind.annotation.RestController;
52
53
54 /**
55  * Controller supplies data to Angular services on the dashboard page.
56  */
57 @RestController
58 @RequestMapping("/portalApi/dashboard")
59 public class DashboardController extends EPRestrictedBaseController {
60
61         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
62
63         @Autowired
64         private DashboardSearchService searchService;
65
66         public enum WidgetCategory {
67                 EVENTS, NEWS, IMPORTANTRESOURCES;
68         }
69
70         /**
71          * Validates the resource type parameter.
72          * 
73          * @param resourceType
74          * @return True if known in the enum WidgetCategory, else false.
75          */
76         private boolean isValidResourceType(String resourceType) {
77                 if (resourceType == null)
78                         return false;
79                 for (WidgetCategory wc : WidgetCategory.values())
80                         if (wc.name().equals(resourceType))
81                                 return true;
82                 return false;
83         }
84
85         /**
86          * Gets all widgets of the specified resource type.
87          * 
88          * @param request
89          * @param resourceType
90          *            Request parameter.
91          * @return Rest response wrapped around a CommonWidgetMeta object.
92          */
93         @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
94         public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
95                         @RequestParam String resourceType) {
96                 if (!isValidResourceType(resourceType))
97                         return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.ERROR,
98                                         "Unexpected resource type " + resourceType, null);
99                 return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
100                                 searchService.getWidgetData(resourceType));
101         }
102
103         /**
104          * Saves a batch of events, news or resources.
105          * 
106          * @param commonWidgetMeta
107          *            read from POST body.
108          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
109          */
110         @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
111         public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
112                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
113                 if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
114                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
115                                         "Category cannot be null or empty");
116                 if (!isValidResourceType(commonWidgetMeta.getCategory()))
117                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
118                                         "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
119                 // validate dates
120                 for (CommonWidget cw : commonWidgetMeta.getItems()) {
121                         String err = validateCommonWidget(cw);
122                         if (err != null)
123                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
124                 }
125                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
126                                 searchService.saveWidgetDataBulk(commonWidgetMeta));
127         }
128
129         /**
130          * Saves one: event, news or resource
131          * 
132          * @param commonWidget
133          *            read from POST body
134          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
135          */
136         @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
137         public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
138                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
139                 if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals(""))
140                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
141                                         "Category cannot be null or empty");
142                 String err = validateCommonWidget(commonWidget);
143                 if (err != null)
144                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
145                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
146                                 searchService.saveWidgetData(commonWidget));
147         }
148
149         /**
150          * Used by the validate function
151          */
152         private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
153
154         /**
155          * Validates the content of a common widget.
156          * 
157          * @param cw
158          * @return null on success; an error message if validation fails.
159          * @throws Exception
160          */
161         private String validateCommonWidget(CommonWidget cw) {
162                 if (!isValidResourceType(cw.getCategory()))
163                         return "Invalid category: " + cw.getCategory();
164                 if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
165                         return "Title is missing";
166                 if (cw.getHref() == null || cw.getHref().trim().length() == 0)
167                         return "HREF is missing";
168                 if (!cw.getHref().toLowerCase().startsWith("http"))
169                         return "HREF does not start with http";
170                 if (cw.getSortOrder() == null)
171                         return "Sort order is null";
172                 if (WidgetCategory.EVENTS.name().equals(cw.getCategory())) {
173                         if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
174                                 return "Date is missing";
175                         try {
176                                 yearMonthDayFormat.setLenient(false);
177                                 Date date = yearMonthDayFormat.parse(cw.getEventDate());
178                                 if (date == null)
179                                         return "Failed to parse date " + cw.getEventDate();
180                         } catch (ParseException ex) {
181                                 return ex.toString();
182                         }
183                 }
184                 return null;
185         }
186
187         /**
188          * Deletes one: event, news or resource
189          * 
190          * @param commonWidget
191          *            read from POST body
192          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
193          */
194         @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
195         public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
196                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
197                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
198                                 searchService.deleteWidgetData(commonWidget));
199         }
200
201         /**
202          * Searches all portal for the input string.
203          * 
204          * @param request
205          * @param searchString
206          * @return Rest response wrapped around a Map of String to List of Search
207          *         Result Item.
208          */
209         @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
210         public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
211                         @RequestParam String searchString) {
212
213                 if (searchString != null)
214                         searchString = searchString.trim();
215                 EPUser user = EPUserUtils.getUserSession(request);
216                 try {
217                         if (user == null) {
218                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
219                                                 "searchPortal: User object is null? - check logs",
220                                                 new HashMap<String, List<SearchResultItem>>());
221                         } else if (searchString == null || searchString.length() == 0) {
222                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
223                                                 new HashMap<String, List<SearchResultItem>>());
224                         } else {
225                                 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
226                                                 user.getLoginId(), searchString);
227                                 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
228                                                 searchString);
229                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
230                         }
231                 } catch (Exception e) {
232                         logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
233                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
234                                         new HashMap<String, List<SearchResultItem>>());
235                 }
236         }
237
238         /**
239          * Gets all active users.
240          * 
241          * @param request
242          * @return Rest response wrapped around a list of String
243          */
244         @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
245         public PortalRestResponse<List<Object[]>> getActiveUsers(HttpServletRequest request) {
246                 List<Object[]> activeUsers = null;
247                 List<Object[]> onlineUsers = new ArrayList<>();
248                 try {
249                         EPUser user = EPUserUtils.getUserSession(request);
250                         String userId = user.getOrgUserId();
251
252                         activeUsers = searchService.getRelatedUserVOs(userId);
253                         HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName();
254                         for (Object[] users : activeUsers) {
255                                 if (usersSet.contains(users[0])) {
256                                         onlineUsers.add(users);
257                                 }
258                         }
259                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", onlineUsers);
260                 } catch (Exception e) {
261                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
262                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
263                 }
264         //      return onlineUsers;
265         }
266         
267         /**
268          * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
269          * 
270          * @param request
271          * @return Rest response wrapped around a number that is the number of milliseconds.
272          */
273         @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
274         public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
275                 PortalRestResponse<String> portalRestResponse = null;
276                 try {
277                         String updateRate = SystemProperties.getProperty(EPSystemProperties.ONLINE_USER_UPDATE_RATE);   
278                         String updateDuration = SystemProperties.getProperty(EPSystemProperties.ONLINE_USER_UPDATE_DURATION);                           
279                         Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
280                         Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
281                         Map<String, String> results = new HashMap<String,String>();
282                         results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
283                         results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));                     
284                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
285                 } catch (Exception e) {
286                         logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
287                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
288                 }               
289         }
290
291         /**
292          * Gets the window width threshold for collapsing right menu from system.properties.
293          * 
294          * @param request
295          * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
296          */
297         @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
298         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
299                 PortalRestResponse<String> portalRestResponse = null;
300                 try {
301                         String windowWidthString = SystemProperties.getProperty(EPSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);  
302                         Integer windowWidth = Integer.valueOf(windowWidthString);
303                         Map<String, String> results = new HashMap<String,String>();
304                         results.put("windowWidth", String.valueOf(windowWidth));
305                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
306                 } catch (Exception e) {
307                         logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
308                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
309                 }               
310         }
311
312
313         /**
314          * Gets the window width threshold for collapsing left menu from system.properties.
315          * 
316          * @param request
317          * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
318          */
319         @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
320         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
321                 PortalRestResponse<String> portalRestResponse = null;
322                 try {
323                         String windowWidthString = SystemProperties.getProperty(EPSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);   
324                         Integer windowWidth = Integer.valueOf(windowWidthString);
325                         Map<String, String> results = new HashMap<String,String>();
326                         results.put("windowWidth", String.valueOf(windowWidth));
327                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
328                 } catch (Exception e) {
329                         logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
330                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
331                 }               
332         }
333         
334         
335         
336         /**
337          * Gets only those users that are 'related' to the currently logged-in user.
338          * 
339          * @param request
340          * @return Rest response wrapped around a List of String
341          */
342         @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
343         public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
344                 EPUser user = EPUserUtils.getUserSession(request);
345                 try {
346                         if (user == null) {
347                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
348                                                 new ArrayList<>());
349                         } else {
350                                 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
351                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
352                                                 searchService.getRelatedUsers(user.getLoginId()));
353                         }
354                 } catch (Exception e) {
355                         logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
356                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
357                                         new ArrayList<>());
358                 }
359         }
360
361 }