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