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