Tests coverage up and some minor bug fixes
[portal.git] / portal-BE / src / main / java / org / onap / portal / controller / WidgetsController.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.controller;
42
43 import java.io.IOException;
44 import java.security.Principal;
45 import java.util.List;
46 import javax.servlet.http.HttpServletRequest;
47 import javax.servlet.http.HttpServletResponse;
48 import org.onap.portal.domain.db.fn.FnUser;
49 import org.onap.portal.domain.dto.transport.FieldsValidator;
50 import org.onap.portal.domain.dto.transport.OnboardingWidget;
51 import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization;
52 import org.onap.portal.exception.NotValidDataException;
53 import org.onap.portal.logging.aop.EPAuditLog;
54 import org.onap.portal.service.AdminRolesService;
55 import org.onap.portal.service.PersUserWidgetService;
56 import org.onap.portal.service.WidgetService;
57 import org.onap.portal.service.fn.FnUserService;
58 import org.onap.portal.utils.EcompPortalUtils;
59 import org.onap.portal.validation.DataValidator;
60 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.context.annotation.EnableAspectJAutoProxy;
63 import org.springframework.http.MediaType;
64 import org.springframework.security.access.prepost.PreAuthorize;
65 import org.springframework.web.bind.annotation.DeleteMapping;
66 import org.springframework.web.bind.annotation.GetMapping;
67 import org.springframework.web.bind.annotation.PathVariable;
68 import org.springframework.web.bind.annotation.PostMapping;
69 import org.springframework.web.bind.annotation.PutMapping;
70 import org.springframework.web.bind.annotation.RequestBody;
71 import org.springframework.web.bind.annotation.RestController;
72
73 @EPAuditLog
74 @RestController
75 @EnableAspectJAutoProxy
76 public class WidgetsController {
77
78        private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsController.class);
79
80        private final FnUserService fnUserService;
81        private final WidgetService widgetService;
82        private final AdminRolesService adminRolesService;
83        private final DataValidator dataValidator;
84        private final PersUserWidgetService persUserWidgetService;
85
86        @Autowired
87        public WidgetsController(final FnUserService fnUserService, final WidgetService widgetService,
88                final AdminRolesService adminRolesService, final DataValidator dataValidator,
89                final PersUserWidgetService persUserWidgetService) {
90               this.fnUserService = fnUserService;
91               this.widgetService = widgetService;
92               this.adminRolesService = adminRolesService;
93               this.dataValidator = dataValidator;
94               this.persUserWidgetService = persUserWidgetService;
95        }
96
97        @GetMapping(value = {"/portalApi/widgets"}, produces = MediaType.APPLICATION_JSON_VALUE)
98        public List<OnboardingWidget> getOnboardingWidgets(Principal principal, HttpServletRequest request,
99                HttpServletResponse response) {
100               FnUser user = fnUserService.loadUserByUsername(principal.getName());
101               List<OnboardingWidget> onboardingWidgets = null;
102               if (user.getGuest()) {
103                      EcompPortalUtils.setBadPermissions(user, response, "getOnboardingWidgets");
104               } else {
105                      String getType = request.getHeader("X-Widgets-Type");
106                      if (!getType.isEmpty() && ("managed".equals(getType) || "all".equals(getType))) {
107                             onboardingWidgets = widgetService.getOnboardingWidgets(user, "managed".equals(getType));
108                      } else {
109                             logger.debug(EELFLoggerDelegate.debugLogger,
110                                     "WidgetsController.getOnboardingApps - request must contain header 'X-Widgets-Type' with 'all' or 'managed'");
111                             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
112                      }
113               }
114
115               EcompPortalUtils
116                       .logAndSerializeObject(logger, "/portalApi/widgets", "GET result =", response.getStatus());
117               return onboardingWidgets;
118        }
119
120        @PutMapping(value = {"/portalApi/widgets/{widgetId}"}, produces = MediaType.APPLICATION_JSON_VALUE)
121        @PreAuthorize("hasRole('System_Administrator')")
122        public FieldsValidator putOnboardingWidget(Principal principal, @PathVariable("widgetId") Long widgetId,
123                @RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) {
124               FnUser user = fnUserService.loadUserByUsername(principal.getName());
125               FieldsValidator fieldsValidator = null;
126
127               assert onboardingWidget != null;
128               onboardingWidget.setId(widgetId);
129               onboardingWidget.normalize();
130               try {
131                      fieldsValidator = widgetService.setOnboardingWidget(user, onboardingWidget);
132                      response.setStatus(fieldsValidator.getHttpStatusCode().intValue());
133               } catch (IllegalArgumentException e) {
134                      fieldsValidator = new FieldsValidator();
135                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE);
136                      fieldsValidator.addProblematicFieldName(e.getMessage());
137                      return fieldsValidator;
138               }
139
140               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets/" + widgetId, "GET result =",
141                       response.getStatus());
142
143               return fieldsValidator;
144        }
145
146        private boolean userHasPermissions(FnUser user, HttpServletResponse response, String invocator) {
147               if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
148                      EcompPortalUtils.setBadPermissions(user, response, invocator);
149                      return false;
150               }
151               return true;
152        }
153
154        @PostMapping(value = {"/portalApi/widgets"}, produces = MediaType.APPLICATION_JSON_VALUE)
155        public FieldsValidator postOnboardingWidget(Principal principal, HttpServletResponse response,
156                @RequestBody OnboardingWidget onboardingWidget) {
157               FnUser user = fnUserService.loadUserByUsername(principal.getName());
158               FieldsValidator fieldsValidator = new FieldsValidator();
159
160               if (onboardingWidget != null) {
161                      if (!dataValidator.isValid(onboardingWidget)) {
162                             fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE);
163                             return fieldsValidator;
164                      }
165               }
166
167               if (userHasPermissions(user, response, "postOnboardingWidget")) {
168                      onboardingWidget.setId(null);
169                      onboardingWidget.normalize();
170                      try {
171                             fieldsValidator = widgetService.setOnboardingWidget(user, onboardingWidget);
172                      } catch (Exception e) {
173                             fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_BAD_REQUEST);
174                      }
175                      response.setStatus(fieldsValidator.getHttpStatusCode().intValue());
176               }
177
178               EcompPortalUtils
179                       .logAndSerializeObject(logger, "/portalApi/widgets", "POST result =", response.getStatus());
180               return fieldsValidator;
181        }
182
183        @DeleteMapping(value = {"/portalApi/widgets/{widgetId}"}, produces = MediaType.APPLICATION_JSON_VALUE)
184        public FieldsValidator deleteOnboardingWidget(Principal principal, HttpServletResponse response,
185                @PathVariable("widgetId") Long widgetId) {
186               FnUser user = fnUserService.loadUserByUsername(principal.getName());
187               FieldsValidator fieldsValidator = null;
188
189               if (userHasPermissions(user, response, "deleteOnboardingWidget")) {
190                      fieldsValidator = widgetService.deleteOnboardingWidget(user, widgetId);
191                      response.setStatus(fieldsValidator.getHttpStatusCode().intValue());
192               }
193
194               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets/" + widgetId, "DELETE result =",
195                       response.getStatus());
196               return fieldsValidator;
197        }
198
199        @PutMapping(value = {"portalApi/widgetCatalogSelection"}, produces = MediaType.APPLICATION_JSON_VALUE)
200        public FieldsValidator putWidgetCatalogSelection(Principal principal,
201                @RequestBody WidgetCatalogPersonalization persRequest, HttpServletResponse response) throws IOException {
202               FieldsValidator result = new FieldsValidator();
203               FnUser user = fnUserService.loadUserByUsername(principal.getName());
204
205               if (persRequest != null) {
206                      if (!dataValidator.isValid(persRequest)) {
207                             result.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE);
208                             return result;
209                      }
210               }
211               try {
212                      assert persRequest != null;
213                      if (persRequest.getWidgetId() == null || user == null) {
214                             EcompPortalUtils.setBadPermissions(user, response, "putWidgetCatalogSelection");
215                      } else {
216                             persUserWidgetService
217                                     .setPersUserAppValue(user, persRequest.getWidgetId(), persRequest.getSelect());
218                      }
219               } catch (Exception e) {
220                      logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", e);
221                      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
222               }
223               result.setHttpStatusCode((long) HttpServletResponse.SC_OK);
224               return result;
225        }
226 }