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