2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.controller;
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;
49 import javax.servlet.http.HttpServletRequest;
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;
77 @RequestMapping("/portalApi/search")
78 public class DashboardSearchResultController extends EPRestrictedBaseController {
79 private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
81 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class);
84 private DashboardSearchService searchService;
87 * Gets all widgets by type: NEW or RESOURCE
92 * @return Rest response wrapped around a CommonWidgetMeta object.
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", "");
100 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
101 searchService.getWidgetData(resourceType));
105 * Saves all: news and resources
107 * @param commonWidgetMeta
108 * read from POST body.
109 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
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");
125 for (CommonWidget cw : commonWidgetMeta.getItems()) {
126 String err = validateCommonWidget(cw);
128 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
130 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
131 searchService.saveWidgetDataBulk(commonWidgetMeta));
135 * Saves one: news or resource
137 * @param commonWidget
138 * read from POST body
139 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
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");
154 String err = validateCommonWidget(commonWidget);
156 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
157 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
158 searchService.saveWidgetData(commonWidget));
162 * Used by the validate function
164 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
167 * Validates the content of a common widget.
170 * @return null on success; an error message if validation fails.
173 private String validateCommonWidget(CommonWidget cw) {
175 if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0)
176 yearMonthDayFormat.parse(cw.getEventDate());
177 } catch (ParseException ex) {
178 return ex.toString();
184 * Deletes one: news or resource
186 * @param commonWidget
187 * read from POST body
188 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
199 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
200 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
201 searchService.deleteWidgetData(commonWidget));
205 * Searches all portal for the input string.
208 * @param searchString
209 * @return Rest response wrapped around a Map of String to List of Search
212 @GetMapping(value = "/allPortal", produces = "application/json")
213 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
214 @RequestParam String searchString) {
216 EPUser user = EPUserUtils.getUserSession(request);
219 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
220 "searchPortal: User object is null? - check logs",
222 } else if (searchString == null || searchString.trim().length() == 0) {
223 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
225 }else if (stringIsNotSafeHtml(searchString)){
226 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not valid",
229 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
230 user.getLoginId(), searchString);
231 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
233 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
235 } catch (Exception e) {
236 logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
237 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
243 * Gets all active users.
245 * TODO: should only the superuser be allowed to use this API?
248 * @return Rest response wrapped around a list of String
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<>();
255 EPUser user = EPUserUtils.getUserSession(request);
256 String userId = user.getOrgUserId();
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);
266 } catch (Exception e) {
267 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
273 * Gets only those users that are 'related' to the currently logged-in user.
276 * @return Rest response wrapped around a List of String
278 @GetMapping(value = "/relatedUsers", produces = "application/json")
279 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
280 EPUser user = EPUserUtils.getUserSession(request);
283 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
286 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
287 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
288 searchService.getRelatedUsers(user.getLoginId()));
290 } catch (Exception e) {
291 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
292 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
297 private boolean stringIsNotSafeHtml(String string){
298 SecureString secureString = new SecureString(string);
300 Validator validator = VALIDATOR_FACTORY.getValidator();
302 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
303 return !constraintViolations.isEmpty();