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