2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.service;
40 import java.util.ArrayList;
41 import java.util.List;
43 import javax.annotation.PostConstruct;
44 import javax.servlet.http.HttpServletResponse;
46 import org.hibernate.Session;
47 import org.hibernate.SessionFactory;
48 import org.hibernate.Transaction;
49 import org.hibernate.criterion.Criterion;
50 import org.hibernate.criterion.Restrictions;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.context.annotation.EnableAspectJAutoProxy;
53 import org.springframework.stereotype.Service;
54 import org.springframework.transaction.annotation.Transactional;
55 import org.onap.portalapp.portal.domain.EPUser;
56 import org.onap.portalapp.portal.domain.EPUserApp;
57 import org.onap.portalapp.portal.domain.Widget;
58 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
59 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
60 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
61 import org.onap.portalapp.portal.transport.FieldsValidator;
62 import org.onap.portalapp.portal.transport.OnboardingWidget;
63 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
64 import org.onap.portalapp.portal.utils.EcompPortalUtils;
65 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
66 import org.onap.portalsdk.core.service.DataAccessService;
67 import org.onap.portalsdk.core.util.SystemProperties;
69 @Service("widgetService")
71 @org.springframework.context.annotation.Configuration
72 @EnableAspectJAutoProxy
74 public class WidgetServiceImpl implements WidgetService {
76 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetServiceImpl.class);
78 private static final String baseSqlToken = " widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL"
79 + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
81 private String validAppsFilter = "";
83 private Long LONG_ECOMP_APP_ID = 1L;
84 private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
85 private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
87 private static final String urlField = "url";
89 private static final String nameField = "name";
91 AdminRolesService adminRolesService;
93 private SessionFactory sessionFactory;
95 private DataAccessService dataAccessService;
100 validAppsFilter = " AND app.ENABLED = 'Y' AND app.APP_ID != " + SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
101 ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
102 LONG_ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
103 } catch(Exception e) {
104 logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
108 private String sqlWidgetsForAllApps() {
109 return "SELECT" + baseSqlToken + validAppsFilter;
112 private String sqlWidgetsForAllAppsWhereUserIsAdmin(Long userId) {
113 return "SELECT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + userId
114 + " AND FN_USER_ROLE.ROLE_ID = " + ACCOUNT_ADMIN_ROLE_ID + validAppsFilter;
117 private String sqlWidgetsForAllAppsWhereUserHasAnyRole(Long userId) {
118 return "SELECT DISTINCT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
119 + userId + validAppsFilter;
122 @SuppressWarnings("unchecked")
124 public List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed) {
125 List<OnboardingWidget> onboardingWidgets = new ArrayList<OnboardingWidget>();
127 if (adminRolesService.isSuperAdmin(user)) {
128 sql = this.sqlWidgetsForAllApps();
129 } else if (managed) {
130 if (adminRolesService.isAccountAdmin(user)) {
131 sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId());
133 } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
134 sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId());
137 onboardingWidgets = dataAccessService.executeSQLQuery(sql, OnboardingWidget.class, null);
139 return onboardingWidgets;
142 private static final Object syncRests = new Object();
144 private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
146 List<EPUserApp> userRoles = getAdminUserRoles(userId, appId);
147 return (userRoles.size() > 0);
152 @SuppressWarnings("unchecked")
153 private List<EPUserApp> getAdminUserRoles(Long userId, Long appId) {
154 List<Criterion> restrictionsList = new ArrayList<Criterion>();
155 Criterion userIdCriterion = Restrictions.eq("userId",userId);
156 Criterion roleIDCriterion = Restrictions.eq("role.id", ACCOUNT_ADMIN_ROLE_ID);
157 Criterion appIDCriterion = Restrictions.eq("app.id", appId);
158 restrictionsList.add(Restrictions.and(userIdCriterion, roleIDCriterion,appIDCriterion));
159 return (List<EPUserApp>) dataAccessService.getList(EPUserApp.class, null, restrictionsList, null);
162 private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
164 List<Widget> widgets = getWidgets(onboardingWidget);
165 boolean dublicatedUrl = false;
166 boolean dublicatedName = false;
167 for (Widget widget : widgets) {
168 if (onboardingWidget.id != null && onboardingWidget.id.equals(widget.getId())) {
169 // widget should not be compared with itself
172 if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.url)) {
173 dublicatedUrl = true;
174 if (dublicatedName) {
178 if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.name) && widget.getAppId().equals(onboardingWidget.appId)) {
179 dublicatedName = true;
185 if (dublicatedUrl || dublicatedName) {
187 fieldsValidator.addProblematicFieldName(urlField);
189 if (dublicatedName) {
190 fieldsValidator.addProblematicFieldName(nameField);
192 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
193 fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR;
197 @SuppressWarnings("unchecked")
198 private List<Widget> getWidgets(OnboardingWidget onboardingWidget) {
199 List<Criterion> restrictionsList = new ArrayList<Criterion>();
200 Criterion urlCriterion = Restrictions.eq("url", onboardingWidget.url);
201 Criterion nameCriterion = Restrictions.eq("name", onboardingWidget.name);
202 restrictionsList.add(Restrictions.or(urlCriterion, nameCriterion));
203 return (List<Widget>) dataAccessService.getList(Widget.class, null, restrictionsList, null);
206 private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
207 boolean result = false;
208 Session localSession = null;
209 Transaction transaction = null;
211 localSession = sessionFactory.openSession();
212 transaction = localSession.beginTransaction();
214 if (onboardingWidget.id == null) {
215 widget = new Widget();
217 widget = (Widget) localSession.get(Widget.class, onboardingWidget.id);
219 widget.setAppId(onboardingWidget.appId);
220 widget.setName(onboardingWidget.name);
221 widget.setWidth(onboardingWidget.width);
222 widget.setHeight(onboardingWidget.height);
223 widget.setUrl(onboardingWidget.url);
224 localSession.saveOrUpdate(widget);
225 transaction.commit();
227 } catch (Exception e) {
228 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
229 EcompPortalUtils.rollbackTransaction(transaction, "applyOnboardingWidget rollback, exception = " + e);
231 EcompPortalUtils.closeLocalSession(localSession, "applyOnboardingWidget");
234 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
238 private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
239 FieldsValidator fieldsValidator = new FieldsValidator();
240 if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.appId)) {
241 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
242 return fieldsValidator;
244 synchronized (syncRests) {
245 // onboardingWidget.id is null for POST and not null for PUT
246 if (onboardingWidget.id == null) {
247 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
249 Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidget.id, null);
250 if (widget == null || widget.getId() == null) {
252 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
253 return fieldsValidator;
255 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
257 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
258 this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
261 return fieldsValidator;
265 public FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget) {
266 if (onboardingWidget.name.length() == 0 || onboardingWidget.url.length() == 0 || onboardingWidget.appId == null
267 || onboardingWidget.appId.equals(LONG_ECOMP_APP_ID) || onboardingWidget.width.intValue() <= 0 || onboardingWidget.height.intValue() <= 0) {
268 if (onboardingWidget.appId.equals(LONG_ECOMP_APP_ID)) {
270 FieldsValidator fieldsValidator = new FieldsValidator();
271 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
272 return fieldsValidator;
274 return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget);
278 public FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId) {
279 FieldsValidator fieldsValidator = new FieldsValidator();
280 synchronized (syncRests) {
281 Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidgetId, null);
282 if (widget != null && widget.getId() != null) { // widget exists
283 if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(), widget.getAppId())) {
284 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
286 boolean result = false;
287 Session localSession = null;
288 Transaction transaction = null;
290 localSession = sessionFactory.openSession();
291 transaction = localSession.beginTransaction();
292 localSession.delete(localSession.get(Widget.class, onboardingWidgetId));
293 transaction.commit();
295 } catch (Exception e) {
296 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
297 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingWidget rollback, exception = " + e);
299 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingWidget");
302 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
307 return fieldsValidator;