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.RequestMethod;
72 import org.springframework.web.bind.annotation.RequestParam;
73 import org.springframework.web.bind.annotation.RestController;
76 @RequestMapping("/portalApi/search")
77 public class DashboardSearchResultController extends EPRestrictedBaseController {
78 private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
80 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class);
83 private DashboardSearchService searchService;
86 * Gets all widgets by type: NEW or RESOURCE
91 * @return Rest response wrapped around a CommonWidgetMeta object.
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", "");
99 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
100 searchService.getWidgetData(resourceType));
104 * Saves all: news and resources
106 * @param commonWidgetMeta
107 * read from POST body.
108 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
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");
124 for (CommonWidget cw : commonWidgetMeta.getItems()) {
125 String err = validateCommonWidget(cw);
127 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
129 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
130 searchService.saveWidgetDataBulk(commonWidgetMeta));
134 * Saves one: news or resource
136 * @param commonWidget
137 * read from POST body
138 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
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");
153 String err = validateCommonWidget(commonWidget);
155 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
156 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
157 searchService.saveWidgetData(commonWidget));
161 * Used by the validate function
163 private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
166 * Validates the content of a common widget.
169 * @return null on success; an error message if validation fails.
172 private String validateCommonWidget(CommonWidget cw) {
174 if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0)
175 yearMonthDayFormat.parse(cw.getEventDate());
176 } catch (ParseException ex) {
177 return ex.toString();
183 * Deletes one: news or resource
185 * @param commonWidget
186 * read from POST body
187 * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
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");
198 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
199 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
200 searchService.deleteWidgetData(commonWidget));
204 * Searches all portal for the input string.
207 * @param searchString
208 * @return Rest response wrapped around a Map of String to List of Search
211 @RequestMapping(value = "/allPortal", method = RequestMethod.GET, produces = "application/json")
212 public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
213 @RequestParam String searchString) {
215 EPUser user = EPUserUtils.getUserSession(request);
218 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
219 "searchPortal: User object is null? - check logs",
221 } else if (searchString == null || searchString.trim().length() == 0) {
222 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
224 }else if (stringIsNotSafeHtml(searchString)){
225 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not valid",
228 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
229 user.getLoginId(), searchString);
230 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
232 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
234 } catch (Exception e) {
235 logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
236 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
242 * Gets all active users.
244 * TODO: should only the superuser be allowed to use this API?
247 * @return Rest response wrapped around a list of String
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<>();
254 EPUser user = EPUserUtils.getUserSession(request);
255 String userId = user.getOrgUserId();
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);
265 } catch (Exception e) {
266 logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
272 * Gets only those users that are 'related' to the currently logged-in user.
275 * @return Rest response wrapped around a List of String
277 @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
278 public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
279 EPUser user = EPUserUtils.getUserSession(request);
282 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
285 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
286 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
287 searchService.getRelatedUsers(user.getLoginId()));
289 } catch (Exception e) {
290 logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
291 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
296 private boolean stringIsNotSafeHtml(String string){
297 SecureString secureString = new SecureString(string);
299 Validator validator = VALIDATOR_FACTORY.getValidator();
301 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
302 return !constraintViolations.isEmpty();