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