nexus site path corrected
[portal.git] / ecomp-portal-BE / src / main / java / org / openecomp / portalapp / portal / controller / DashboardSearchResultController.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.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.servlet.http.HttpServletRequest;
31
32 import org.openecomp.portalapp.controller.EPRestrictedBaseController;
33 import org.openecomp.portalapp.portal.domain.EPUser;
34 import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
35 import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
36 import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
37 import org.openecomp.portalapp.portal.service.DashboardSearchService;
38 import org.openecomp.portalapp.portal.transport.CommonWidget;
39 import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
40 import org.openecomp.portalapp.util.EPUserUtils;
41 import org.openecomp.portalsdk.core.domain.support.CollaborateList;
42 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.web.bind.annotation.RequestBody;
45 import org.springframework.web.bind.annotation.RequestMapping;
46 import org.springframework.web.bind.annotation.RequestMethod;
47 import org.springframework.web.bind.annotation.RequestParam;
48 import org.springframework.web.bind.annotation.RestController;
49
50 @RestController
51 @RequestMapping("/portalApi/search")
52 public class DashboardSearchResultController extends EPRestrictedBaseController {
53
54         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class);
55
56         @Autowired
57         private DashboardSearchService searchService;
58
59         /**
60          * Gets all widgets by type: NEW or RESOURCE
61          * 
62          * @param request
63          * @param resourceType
64          *            Request parameter.
65          * @return Rest response wrapped around a CommonWidgetMeta object.
66          */
67         @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
68         public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
69                         @RequestParam String resourceType) {
70                 return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
71                                 searchService.getWidgetData(resourceType));
72         }
73
74         /**
75          * Saves all: news and resources
76          * 
77          * @param commonWidgetMeta
78          *            read from POST body.
79          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
80          */
81         @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
82         public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
83                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
84                 if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
85                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
86                                         "Category cannot be null or empty");
87                 // validate dates
88                 for (CommonWidget cw : commonWidgetMeta.getItems()) {
89                         String err = validateCommonWidget(cw);
90                         if (err != null)
91                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
92                 }
93                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
94                                 searchService.saveWidgetDataBulk(commonWidgetMeta));
95         }
96
97         /**
98          * Saves one: news or resource
99          * 
100          * @param commonWidget
101          *            read from POST body
102          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
103          */
104         @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
105         public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
106                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
107                 if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals(""))
108                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
109                                         "Cateogry cannot be null or empty");
110                 String err = validateCommonWidget(commonWidget);
111                 if (err != null)
112                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
113                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
114                                 searchService.saveWidgetData(commonWidget));
115         }
116
117         /**
118          * Used by the validate function
119          */
120         private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
121
122         /**
123          * Validates the content of a common widget.
124          * 
125          * @param cw
126          * @return null on success; an error message if validation fails.
127          * @throws Exception
128          */
129         private String validateCommonWidget(CommonWidget cw) {
130                 try {
131                         if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0)
132                                 yearMonthDayFormat.parse(cw.getEventDate());
133                 } catch (ParseException ex) {
134                         return ex.toString();
135                 }
136                 return null;
137         }
138
139         /**
140          * Deletes one: news or resource
141          * 
142          * @param commonWidget
143          *            read from POST body
144          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
145          */
146         @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
147         public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
148                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
149                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
150                                 searchService.deleteWidgetData(commonWidget));
151         }
152
153         /**
154          * Searches all portal for the input string.
155          * 
156          * @param request
157          * @param searchString
158          * @return Rest response wrapped around a Map of String to List of Search
159          *         Result Item.
160          */
161         @RequestMapping(value = "/allPortal", method = RequestMethod.GET, produces = "application/json")
162         public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
163                         @RequestParam String searchString) {
164
165                 EPUser user = EPUserUtils.getUserSession(request);
166                 try {
167                         if (user == null) {
168                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
169                                                 "searchPortal: User object is null? - check logs",
170                                                 new HashMap<String, List<SearchResultItem>>());
171                         } else if (searchString == null || searchString.trim().length() == 0) {
172                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
173                                                 new HashMap<String, List<SearchResultItem>>());
174                         } else {
175                                 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
176                                                 user.getLoginId(), searchString);
177                                 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
178                                                 searchString);
179                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
180                         }
181                 } catch (Exception e) {
182                         logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
183                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
184                                         new HashMap<String, List<SearchResultItem>>());
185                 }
186         }
187
188         /**
189          * Gets all active users.
190          * 
191          * TODO: should only the superuser be allowed to use this API?
192          * 
193          * @param request
194          * @return Rest response wrapped around a list of String
195          */
196         @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
197         public List<String> getActiveUsers(HttpServletRequest request) {
198                 List<String> activeUsers = null;
199                 List<String> onlineUsers = new ArrayList<>();
200                 try {
201                         EPUser user = EPUserUtils.getUserSession(request);
202                         String userId = user.getOrgUserId();
203
204                         activeUsers = searchService.getRelatedUsers(userId);
205                         HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName();
206                         for (String users : activeUsers) {
207                                 if (usersSet.contains(users)) {
208                                         onlineUsers.add(users);
209                                 }
210                         }
211
212                 } catch (Exception e) {
213                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
214                 }
215                 return onlineUsers;
216         }
217
218         /**
219          * Gets only those users that are 'related' to the currently logged-in user.
220          * 
221          * @param request
222          * @return Rest response wrapped around a List of String
223          */
224         @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
225         public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
226                 EPUser user = EPUserUtils.getUserSession(request);
227                 try {
228                         if (user == null) {
229                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
230                                                 new ArrayList<>());
231                         } else {
232                                 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
233                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
234                                                 searchService.getRelatedUsers(user.getLoginId()));
235                         }
236                 } catch (Exception e) {
237                         logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
238                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
239                                         new ArrayList<>());
240                 }
241         }
242
243 }