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