Null check for ClientResponse in PolicyUril.java
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / controller / ExternalAppsRestfulController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.openecomp.portalapp.portal.controller;
39
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.Calendar;
43 import java.util.List;
44
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47
48 import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
49 import org.openecomp.portalapp.portal.domain.EPApp;
50 import org.openecomp.portalapp.portal.domain.EPRole;
51 import org.openecomp.portalapp.portal.domain.EPUser;
52 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
53 import org.openecomp.portalapp.portal.service.AdminRolesService;
54 import org.openecomp.portalapp.portal.service.EPLoginService;
55 import org.openecomp.portalapp.portal.service.EPRoleService;
56 import org.openecomp.portalapp.portal.service.FunctionalMenuService;
57 import org.openecomp.portalapp.portal.service.UserNotificationService;
58 import org.openecomp.portalapp.portal.transport.EpNotificationItem;
59 import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
60 import org.openecomp.portalapp.portal.transport.FieldsValidator;
61 import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
62 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
63 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
64 import org.openecomp.portalapp.portal.utils.PortalConstants;
65 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
66 import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
67 import org.slf4j.MDC;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.context.annotation.Configuration;
70 import org.springframework.context.annotation.EnableAspectJAutoProxy;
71 import org.springframework.http.HttpStatus;
72 import org.springframework.web.bind.annotation.ExceptionHandler;
73 import org.springframework.web.bind.annotation.RequestBody;
74 import org.springframework.web.bind.annotation.RequestMapping;
75 import org.springframework.web.bind.annotation.RequestMethod;
76 import org.springframework.web.bind.annotation.ResponseBody;
77 import org.springframework.web.bind.annotation.RestController;
78
79 import io.swagger.annotations.ApiOperation;
80
81 @RestController
82 @RequestMapping(PortalConstants.REST_AUX_API)
83 @Configuration
84 @EnableAspectJAutoProxy
85 @EPAuditLog
86 public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController {
87
88         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class);
89
90         @Autowired
91         private FunctionalMenuService functionalMenuService;
92
93         @Autowired
94         private EPLoginService epLoginService;
95
96         @Autowired
97         private AdminRolesService adminRolesService;
98
99         @Autowired
100         private UserNotificationService userNotificationService;
101
102         @Autowired
103         private EPRoleService epRoleService;
104
105         @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class)
106         @RequestMapping(value = { "/publishNotification" }, method = RequestMethod.POST, produces = "application/json")
107         @ResponseBody
108         public PortalAPIResponse publishNotification(HttpServletRequest request,
109                         @RequestBody EpNotificationItem notificationItem) throws Exception {
110                 String appKey = request.getHeader("uebkey");
111                 EPApp app = findEpApp(appKey);
112                 List<Long> postRoleIds = new ArrayList<Long>();
113                 for (Long roleId : notificationItem.getRoleIds()) {
114                         EPRole role = epRoleService.getRole(app.getId(), roleId);
115                         if (role != null)
116                                 postRoleIds.add(role.getId());
117                 }
118
119                 // --- recreate the user notification object with the POrtal Role Ids
120                 EpNotificationItem postItem = new EpNotificationItem();
121                 postItem.setRoleIds(postRoleIds);
122                 postItem.setIsForAllRoles("N");
123                 postItem.setIsForOnlineUsers("N");
124                 postItem.setActiveYn("Y");
125                 postItem.setPriority(notificationItem.getPriority());
126                 postItem.setMsgHeader(notificationItem.getMsgHeader());
127                 postItem.setMsgDescription(notificationItem.getMsgDescription());
128                 postItem.setStartTime(notificationItem.getStartTime());
129                 postItem.setEndTime(notificationItem.getEndTime());
130                 postItem.setCreatedDate(Calendar.getInstance().getTime());
131                 // default creator to 1 for now
132                 postItem.setCreatorId(PortalConstants.DEFAULT_NOTIFICATION_CREATOR);
133                 // ----
134
135                 try {
136                         userNotificationService.saveNotification(postItem);
137                 } catch (Exception e) {
138                         return new PortalAPIResponse(false, e.getMessage());
139                 }
140
141                 PortalAPIResponse response = new PortalAPIResponse(true, "success");
142                 return response;
143         }
144
145         private EPApp findEpApp(String uebKey) {
146                 List<?> list = null;
147                 StringBuffer criteria = new StringBuffer();
148                 criteria.append(" where ueb_key = '" + uebKey + "'");
149                 list = getDataAccessService().getList(EPApp.class, criteria.toString(), null, null);
150                 return (list == null || list.size() == 0) ? null : (EPApp) list.get(0);
151         }
152
153         @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List")
154         @RequestMapping(value = { "/getFavorites" }, method = RequestMethod.GET, produces = "application/json")
155         public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
156                         HttpServletResponse response) throws Exception {
157                 String loginId = "";
158                 String userAgent = "";
159                 List<FavoritesFunctionalMenuItemJson> favorites = null;
160
161                 loginId = request.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID);
162                 userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
163
164                 EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
165                 logger.info(EELFLoggerDelegate.errorLogger,
166                                 "getFavorites request was received from " + userAgent + " for the user " + loginId + ".");
167                 if (epUser == null || epUser.getId() == null) {
168                         logger.error(EELFLoggerDelegate.errorLogger,
169                                         "No User record found for the LoginId '" + loginId + "' in the database.");
170                         throw new Exception("Received null for Login-Id.");
171                 } else {
172                         favorites = functionalMenuService.getFavoriteItems(epUser.getId());
173                         FieldsValidator fieldsValidator = new FieldsValidator();
174                         response.setStatus(fieldsValidator.httpStatusCode.intValue());
175
176                         EcompPortalUtils.logAndSerializeObject(logger, "/getFavorites", "result = ", favorites);
177                 }
178
179                 return favorites;
180         }
181
182         @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer="List")
183         @RequestMapping(value = {
184                         "/functionalMenuItemsForUser" }, method = RequestMethod.GET, produces = "application/json")
185         public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request,
186                         HttpServletResponse response) throws Exception {
187                 String loginId = "";
188                 String userAgent = "";
189                 List<FunctionalMenuItem> fnMenuItems = null;
190
191                 loginId = request.getHeader("LoginId");
192                 userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
193
194                 EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
195                 logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from "
196                                 + userAgent + " for the user " + loginId + ".");
197                 if (epUser == null || epUser.getId() == null) {
198                         logger.error(EELFLoggerDelegate.errorLogger,
199                                         "No User record found for the LoginId '" + loginId + "' in the database.");
200                         throw new Exception("Received null for Login-Id.");
201                 } else if (adminRolesService.isSuperAdmin(epUser)) {
202                         logger.debug(EELFLoggerDelegate.debugLogger,
203                                         "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
204                         fnMenuItems = functionalMenuService.getFunctionalMenuItems();
205                 } else {
206                         logger.debug(EELFLoggerDelegate.debugLogger,
207                                         "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
208                         fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId());
209                 }
210
211                 FieldsValidator fieldsValidator = new FieldsValidator();
212                 response.setStatus(fieldsValidator.httpStatusCode.intValue());
213
214                 EcompPortalUtils.logAndSerializeObject(logger, "/functionalMenuItemsForUser", "result = ", fnMenuItems);
215
216                 return fnMenuItems;
217         }
218
219         @ExceptionHandler(Exception.class)
220         protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
221                 logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
222                 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
223         }
224 }