Removing attached entity from method argument
[portal.git] / portal-BE / src / main / java / org / onap / portal / service / widget / WidgetService.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.service.widget;
42
43 import java.util.ArrayList;
44 import java.util.List;
45 import java.util.Optional;
46 import javax.persistence.EntityManager;
47 import javax.servlet.http.HttpServletResponse;
48
49 import org.onap.portal.domain.db.fn.FnUser;
50 import org.onap.portal.domain.db.fn.FnUserRole;
51 import org.onap.portal.domain.db.fn.FnWidget;
52 import org.onap.portal.domain.dto.transport.FieldsValidator;
53 import org.onap.portal.domain.dto.transport.OnboardingWidget;
54 import org.onap.portal.service.AdminRolesService;
55 import org.onap.portal.service.user.FnUserService;
56 import org.onap.portal.service.userRole.FnUserRoleService;
57 import org.onap.portal.utils.EPCommonSystemProperties;
58 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
59 import org.springframework.beans.factory.annotation.Autowired;
60 import org.springframework.context.annotation.EnableAspectJAutoProxy;
61 import org.springframework.security.access.prepost.PreAuthorize;
62 import org.springframework.stereotype.Service;
63 import org.springframework.transaction.annotation.Transactional;
64
65 @Service
66 @Transactional
67 @EnableAspectJAutoProxy
68 public class WidgetService {
69
70        private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetService.class);
71        private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
72
73        private static final String baseSqlToken =
74            " new org.onap.portal.domain.dto.transport.OnboardingWidget("
75                + "widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,"
76                + "app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,"
77                + "widget.WDG_URL, widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,widget.WDG_URL) from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
78
79        private static final String urlField = "url";
80        private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(
81            EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
82        private static final String nameField = "name";
83        private final AdminRolesService adminRolesService;
84        private final EntityManager entityManager;
85        private final FnWidgetDao fnWidgetDao;
86        private final FnUserService fnUserService;
87        private final FnUserRoleService fnUserRoleService;
88        private static final Object syncRests = new Object();
89
90        @Autowired
91        public WidgetService(final AdminRolesService adminRolesService, final EntityManager entityManager,
92            final FnWidgetDao fnWidgetDao, FnUserService fnUserService,
93            FnUserRoleService fnUserRoleService) {
94               this.adminRolesService = adminRolesService;
95               this.entityManager = entityManager;
96               this.fnWidgetDao = fnWidgetDao;
97               this.fnUserService = fnUserService;
98               this.fnUserRoleService = fnUserRoleService;
99        }
100
101        @PreAuthorize("hasRole('System_Administrator')")
102        public FieldsValidator setOnboardingWidget(final Long userId, final OnboardingWidget onboardingWidget) {
103               return this.updateOrSaveWidget(true, userId, onboardingWidget);
104        }
105
106        public List<OnboardingWidget> getOnboardingWidgets(final String orgUserId, final long userId,  final boolean managed) {
107               FnUser user = fnUserService.getUser(userId).get();
108               if (adminRolesService.isSuperAdmin(orgUserId)){
109                      return entityManager.createQuery(sqlWidgetsForAllApps(), OnboardingWidget.class).getResultList();
110               } else if (managed) {
111                      if (adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps())) {
112                             return entityManager
113                                 .createQuery(sqlWidgetsForAllAppsWhereUserIsAdmin(), OnboardingWidget.class)
114                                 .setParameter("USERID", userId).getResultList();
115                      }
116               } else if (adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) || adminRolesService.isUser(userId)) {
117                      return entityManager
118                          .createQuery(sqlWidgetsForAllAppsWhereUserHasAnyRole(), OnboardingWidget.class)
119                          .setParameter("USERID", userId).getResultList();
120               }
121               return new ArrayList<>();
122        }
123
124        public FnWidget saveOne(final FnWidget widget) {
125               return fnWidgetDao.saveAndFlush(widget);
126        }
127
128        @PreAuthorize("hasRole('System_Administrator')")
129        public FieldsValidator deleteOnboardingWidget(final String orgUserId, final long userId, final long onboardingWidgetId) {
130               FieldsValidator fieldsValidator = new FieldsValidator();
131               synchronized (syncRests) {
132                      Optional<FnWidget> widget = this.getOne(onboardingWidgetId);
133                      if (widget.isPresent() && widget.get().getAppId() != null) { // widget exists
134                             if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(orgUserId), userId,
135                                 widget.get().getAppId())) {
136                                    fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN);
137                             } else {
138                                    fnWidgetDao.deleteById(onboardingWidgetId);
139                                    fieldsValidator.setHttpStatusCode(
140                                        (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
141                             }
142                      }
143               }
144               return fieldsValidator;
145        }
146
147        public Optional<FnWidget> getOne(Long id) {
148               return Optional.of(fnWidgetDao.getOne(id));
149        }
150
151        private String sqlWidgetsForAllApps() {
152               return "SELECT" + baseSqlToken;
153        }
154
155        private String sqlWidgetsForAllAppsWhereUserIsAdmin() {
156               return "SELECT" + baseSqlToken
157                   + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = :USERID AND FN_USER_ROLE.ROLE_ID = "
158                   + ACCOUNT_ADMIN_ROLE_ID;
159        }
160
161        private String sqlWidgetsForAllAppsWhereUserHasAnyRole() {
162               return "SELECT DISTINCT" + baseSqlToken
163                   + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
164                   + ":USERID";
165        }
166
167        private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
168               FieldsValidator fieldsValidator = new FieldsValidator();
169               if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.getAppId())) {
170                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN);
171                      return fieldsValidator;
172               }
173               synchronized (syncRests) {
174                      if (onboardingWidget.getId() == null) {
175                             this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
176                      } else {
177                             Optional<FnWidget> widget = this.getOne(onboardingWidget.getId());
178                             if (!widget.isPresent() || widget.get().getAppId() == null) {
179                                    fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_FOUND);
180                                    return fieldsValidator;
181                             }
182                             this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
183                      }
184                      if (fieldsValidator.getHttpStatusCode() == HttpServletResponse.SC_OK) {
185                             this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
186                      }
187               }
188               return fieldsValidator;
189        }
190
191        private boolean isUserAdminOfAppForWidget(final boolean superAdmin, final Long userId, final Long appId) {
192               if (!superAdmin) {
193                      List<FnUserRole> userRoles = fnUserRoleService.getAdminUserRoles(userId, ACCOUNT_ADMIN_ROLE_ID, appId);
194                      return (userRoles.size() > 0);
195               }
196               return true;
197        }
198
199        private void applyOnboardingWidget(final OnboardingWidget onboardingWidget, final FieldsValidator fieldsValidator) {
200               boolean result;
201               FnWidget widget;
202               if (onboardingWidget.getId() == null) {
203                      widget = new FnWidget();
204               } else {
205                      widget = fnWidgetDao.getOne(onboardingWidget.getId());
206               }
207               widget.setAppId(onboardingWidget.getAppId());
208               widget.setName(onboardingWidget.getName());
209               widget.setWidth(onboardingWidget.getWidth());
210               widget.setHeight(onboardingWidget.getHeight());
211               widget.setUrl(onboardingWidget.getUrl());
212               result = widget.equals(fnWidgetDao.saveAndFlush(widget));
213               if (!result) {
214                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
215               }
216        }
217
218        private void validateOnboardingWidget(final OnboardingWidget onboardingWidget,
219            final FieldsValidator fieldsValidator) {
220               List<FnWidget> widgets = getWidgets(onboardingWidget);
221               boolean duplicatedUrl = false;
222               boolean duplicatedName = false;
223               for (FnWidget widget : widgets) {
224                      if (onboardingWidget.getId() != null && onboardingWidget.getId().equals(widget.getWidgetId())) {
225                             // widget should not be compared with itself
226                             continue;
227                      }
228                      if (!duplicatedUrl && widget.getUrl().equals(onboardingWidget.getUrl())) {
229                             duplicatedUrl = true;
230                             if (duplicatedName) {
231                                    break;
232                             }
233                      }
234                      if (!duplicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.getName()) && widget
235                          .getAppId().equals(onboardingWidget.getAppId())) {
236                             duplicatedName = true;
237                             if (duplicatedUrl) {
238                                    break;
239                             }
240                      }
241               }
242               if (duplicatedUrl || duplicatedName) {
243                      if (duplicatedUrl) {
244                             fieldsValidator.addProblematicFieldName(urlField);
245                      }
246                      if (duplicatedName) {
247                             fieldsValidator.addProblematicFieldName(nameField);
248                      }
249                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_CONFLICT);
250                      fieldsValidator.setErrorCode(DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
251               }
252        }
253
254        private List<FnWidget> getWidgets(final OnboardingWidget onboardingWidget) {
255               return fnWidgetDao
256                   .getForUrlNameAndAppId(onboardingWidget.getUrl(), onboardingWidget.getName(), onboardingWidget.getAppId())
257                   .orElse(new ArrayList<>());
258        }
259 }