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