added annotations
[portal.git] / ecomp-portal-BE-os / src / main / java / org / onap / portalapp / portal / controller / DashboardSearchResultController.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.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.onap.portalapp.controller.EPRestrictedBaseController;
51 import org.onap.portalapp.portal.domain.EPUser;
52 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
53 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
54 import org.onap.portalapp.portal.ecomp.model.SearchResultItem;
55 import org.onap.portalapp.portal.service.DashboardSearchService;
56 import org.onap.portalapp.portal.transport.CommonWidget;
57 import org.onap.portalapp.portal.transport.CommonWidgetMeta;
58 import org.onap.portalapp.util.EPUserUtils;
59 import org.onap.portalapp.validation.DataValidator;
60 import org.onap.portalapp.validation.SecureString;
61 import org.onap.portalsdk.core.domain.support.CollaborateList;
62 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.web.bind.annotation.RequestBody;
65 import org.springframework.web.bind.annotation.RequestMapping;
66 import org.springframework.web.bind.annotation.GetMapping;
67 import org.springframework.web.bind.annotation.PostMapping;
68 import org.springframework.web.bind.annotation.PutMapping;
69 import org.springframework.web.bind.annotation.RequestMethod;
70 import org.springframework.web.bind.annotation.RequestParam;
71 import org.springframework.web.bind.annotation.RestController;
72
73 @RestController
74 @RequestMapping("/portalApi/search")
75 public class DashboardSearchResultController extends EPRestrictedBaseController {
76
77         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class);
78         private DataValidator dataValidator = new DataValidator();
79
80         @Autowired
81         private DashboardSearchService searchService;
82
83         /**
84          * Gets all widgets by type: NEW or RESOURCE
85          * 
86          * @param request
87          * @param resourceType
88          *            Request parameter.
89          * @return Rest response wrapped around a CommonWidgetMeta object.
90          */
91         @GetMapping(value = "/widgetData", produces = "application/json")
92         public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
93                         @RequestParam String resourceType) {
94                 if (resourceType !=null){
95                         SecureString secureString = new SecureString(resourceType);
96                         if (!dataValidator.isValid(secureString))
97                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Provided data is invalid", null);
98                 }
99                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
100                                 searchService.getWidgetData(resourceType));
101         }
102
103         /**
104          * Saves all: news and 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         @PostMapping(value = "/widgetDataBulk", 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                 }else {
117                         if(!dataValidator.isValid(commonWidgetMeta))
118                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
119                                         "Category is not valid");
120                 }
121                 // validate dates
122                 for (CommonWidget cw : commonWidgetMeta.getItems()) {
123                         String err = validateCommonWidget(cw);
124                         if (err != null)
125                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
126                 }
127                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
128                                 searchService.saveWidgetDataBulk(commonWidgetMeta));
129         }
130
131         /**
132          * Saves one: news or resource
133          * 
134          * @param commonWidget
135          *            read from POST body
136          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
137          */
138         @PostMapping(value = "/widgetData", produces = "application/json")
139         public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
140                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
141                 if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")){
142                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
143                                         "Cateogry cannot be null or empty");
144                 }else {
145                         if(!dataValidator.isValid(commonWidget))
146                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
147                                         "Category is not valid");
148                 }
149                 String err = validateCommonWidget(commonWidget);
150                 if (err != null)
151                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
152                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
153                                 searchService.saveWidgetData(commonWidget));
154         }
155
156         /**
157          * Used by the validate function
158          */
159         private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
160
161         /**
162          * Validates the content of a common widget.
163          * 
164          * @param cw
165          * @return null on success; an error message if validation fails.
166          * @throws Exception
167          */
168         private String validateCommonWidget(CommonWidget cw) {
169                 try {
170                         if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0)
171                                 yearMonthDayFormat.parse(cw.getEventDate());
172                 } catch (ParseException ex) {
173                         return ex.toString();
174                 }
175                 return null;
176         }
177
178         /**
179          * Deletes one: news or resource
180          * 
181          * @param commonWidget
182          *            read from POST body
183          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
184          */
185         @PostMapping(value = "/deleteData", produces = "application/json")
186         public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
187                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
188                 if(!dataValidator.isValid(commonWidget))
189                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
190                                 "Data is not valid");
191                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
192                                 searchService.deleteWidgetData(commonWidget));
193         }
194
195         /**
196          * Searches all portal for the input string.
197          * 
198          * @param request
199          * @param searchString
200          * @return Rest response wrapped around a Map of String to List of Search
201          *         Result Item.
202          */
203         @GetMapping(value = "/allPortal", produces = "application/json")
204         public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
205                         @RequestParam String searchString) {
206                 if(searchString!=null){
207                         SecureString secureString = new SecureString(searchString);
208                         if(!dataValidator.isValid(secureString)){
209                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
210                                         "searchPortal: User object is invalid",
211                                         null);
212                         }
213                 }
214
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<>());
221                         } else if (searchString == null || searchString.trim().length() == 0) {
222                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
223                                                 new HashMap<>());
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<>());
235                 }
236         }
237
238         /**
239          * Gets all active users.
240          * 
241          * TODO: should only the superuser be allowed to use this API?
242          * 
243          * @param request
244          * @return Rest response wrapped around a list of String
245          */
246         @GetMapping(value = "/activeUsers", produces = "application/json")
247         public List<String> getActiveUsers(HttpServletRequest request) {
248                 List<String> activeUsers = null;
249                 List<String> onlineUsers = new ArrayList<>();
250                 try {
251                         EPUser user = EPUserUtils.getUserSession(request);
252                         String userId = user.getOrgUserId();
253
254                         activeUsers = searchService.getRelatedUsers(userId);
255                         HashSet<String> usersSet = (HashSet<String>) CollaborateList.getInstance().getAllUserName();
256                         for (String users : activeUsers) {
257                                 if (usersSet.contains(users)) {
258                                         onlineUsers.add(users);
259                                 }
260                         }
261
262                 } catch (Exception e) {
263                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
264                 }
265                 return onlineUsers;
266         }
267
268         /**
269          * Gets only those users that are 'related' to the currently logged-in user.
270          * 
271          * @param request
272          * @return Rest response wrapped around a List of String
273          */
274         @GetMapping(value = "/relatedUsers", produces = "application/json")
275         public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
276                 EPUser user = EPUserUtils.getUserSession(request);
277                 try {
278                         if (user == null) {
279                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
280                                                 new ArrayList<>());
281                         } else {
282                                 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
283                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
284                                                 searchService.getRelatedUsers(user.getLoginId()));
285                         }
286                 } catch (Exception e) {
287                         logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
288                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
289                                         new ArrayList<>());
290                 }
291         }
292
293 }