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.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;
80 @RequestMapping("/portalApi/search")
81 public class DashboardSearchResultController extends EPRestrictedBaseController {
82 private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
84 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class);
87 private DashboardSearchService searchService;
90 * Gets all widgets by type: NEW or RESOURCE
95 * @return Rest response wrapped around a CommonWidgetMeta object.
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", "");
103 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
104 searchService.getWidgetData(resourceType));
108 * Saves all: news and resources
110 * @param commonWidgetMeta
111 * read from POST body.
112 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
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");
128 for (CommonWidget cw : commonWidgetMeta.getItems()) {
129 String err = validateCommonWidget(cw);
131 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
133 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
134 searchService.saveWidgetDataBulk(commonWidgetMeta));
138 * Saves one: news or resource
140 * @param commonWidget
141 * read from POST body
142 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
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");
157 String err = validateCommonWidget(commonWidget);
159 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
160 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
161 searchService.saveWidgetData(commonWidget));
165 * Used by the validate function
167 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
170 * Validates the content of a common widget.
173 * @return null on success; an error message if validation fails.
176 private String validateCommonWidget(CommonWidget cw) {
178 if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0)
179 yearMonthDayFormat.parse(cw.getEventDate());
180 } catch (ParseException ex) {
181 return ex.toString();
187 * Deletes one: news or resource
189 * @param commonWidget
190 * read from POST body
191 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
202 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
203 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
204 searchService.deleteWidgetData(commonWidget));
208 * Searches all portal for the input string.
211 * @param searchString
212 * @return Rest response wrapped around a Map of String to List of Search
215 @GetMapping(value = "/allPortal", produces = "application/json")
216 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
217 @RequestParam String searchString) {
219 EPUser user = EPUserUtils.getUserSession(request);
222 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
223 "searchPortal: User object is null? - check logs",
225 } else if (searchString == null || searchString.trim().length() == 0) {
226 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
228 }else if (stringIsNotSafeHtml(searchString)){
229 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not valid",
232 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
233 user.getLoginId(), searchString);
234 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
236 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
238 } catch (Exception e) {
239 logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
240 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
246 * Gets all active users.
248 * TODO: should only the superuser be allowed to use this API?
251 * @return Rest response wrapped around a list of String
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<>();
258 EPUser user = EPUserUtils.getUserSession(request);
259 String userId = user.getOrgUserId();
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);
269 } catch (Exception e) {
270 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
276 * Gets only those users that are 'related' to the currently logged-in user.
279 * @return Rest response wrapped around a List of String
281 @GetMapping(value = "/relatedUsers", produces = "application/json")
282 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
283 EPUser user = EPUserUtils.getUserSession(request);
286 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
289 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
290 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
291 searchService.getRelatedUsers(user.getLoginId()));
293 } catch (Exception e) {
294 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
295 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
300 private boolean stringIsNotSafeHtml(String string){
301 SecureString secureString = new SecureString(string);
303 Validator validator = VALIDATOR_FACTORY.getValidator();
305 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
306 return !constraintViolations.isEmpty();