Security/ Package Name changes
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / WidgetServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 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.onap.portalapp.portal.service;
39
40 import java.util.ArrayList;
41 import java.util.List;
42
43 import javax.annotation.PostConstruct;
44 import javax.servlet.http.HttpServletResponse;
45
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;
68
69 @Service("widgetService")
70 @Transactional
71 @org.springframework.context.annotation.Configuration
72 @EnableAspectJAutoProxy
73 @EPMetricsLog
74 public class WidgetServiceImpl implements WidgetService {
75
76         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetServiceImpl.class);
77
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";
80
81         private String validAppsFilter = "";
82
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);
86
87         private static final String urlField = "url";
88
89         private static final String nameField = "name";
90         @Autowired
91         AdminRolesService adminRolesService;
92         @Autowired
93         private SessionFactory sessionFactory;
94         @Autowired
95         private DataAccessService dataAccessService;
96
97         @PostConstruct
98         private void init() {
99                 try {
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);
105                 }
106         }
107         
108         private String sqlWidgetsForAllApps() {
109                 return "SELECT" + baseSqlToken + validAppsFilter;
110         }
111
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;
115         }
116
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;
120         }
121
122         @SuppressWarnings("unchecked")
123         @Override
124         public List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed) {
125                 List<OnboardingWidget> onboardingWidgets = new ArrayList<OnboardingWidget>();
126                 String sql = null;
127                 if (adminRolesService.isSuperAdmin(user)) {
128                         sql = this.sqlWidgetsForAllApps();
129                 } else if (managed) {
130                         if (adminRolesService.isAccountAdmin(user)) {
131                                 sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId());
132                         }
133                 } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
134                         sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId());
135                 }
136                 if (sql != null) {
137                         onboardingWidgets = dataAccessService.executeSQLQuery(sql, OnboardingWidget.class, null);
138                 }
139                 return onboardingWidgets;
140         }
141
142         private static final Object syncRests = new Object();
143
144         private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
145                 if (!superAdmin) {
146                         List<EPUserApp> userRoles = getAdminUserRoles(userId, appId);
147                         return (userRoles.size() > 0);
148                 }
149                 return true;
150         }
151
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);
160         }
161
162         private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
163                 
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
170                                 continue;
171                         }
172                         if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.url)) {
173                                 dublicatedUrl = true;
174                                 if (dublicatedName) {
175                                         break;
176                                 }
177                         }
178                         if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.name) && widget.getAppId().equals(onboardingWidget.appId)) {
179                                 dublicatedName = true;
180                                 if (dublicatedUrl) {
181                                         break;
182                                 }
183                         }
184                 }
185                 if (dublicatedUrl || dublicatedName) {
186                         if (dublicatedUrl) {
187                                 fieldsValidator.addProblematicFieldName(urlField);
188                         }
189                         if (dublicatedName) {
190                                 fieldsValidator.addProblematicFieldName(nameField);
191                         }
192                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
193                         fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR;
194                 }
195         }
196
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);
204         }
205
206         private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
207                 boolean result = false;
208                 Session localSession = null;
209                 Transaction transaction = null;
210                 try {
211                         localSession = sessionFactory.openSession();
212                         transaction = localSession.beginTransaction();
213                         Widget widget;
214                         if (onboardingWidget.id == null) {
215                                 widget = new Widget();
216                         } else {
217                                 widget = (Widget) localSession.get(Widget.class, onboardingWidget.id);
218                         }
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();
226                         result = true;
227                 } catch (Exception e) {
228                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
229                         EcompPortalUtils.rollbackTransaction(transaction, "applyOnboardingWidget rollback, exception = " + e);
230                 } finally {
231                         EcompPortalUtils.closeLocalSession(localSession, "applyOnboardingWidget");
232                 }
233                 if (!result) {
234                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
235                 }
236         }
237
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;
243                 }
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);
248                         } else {
249                                 Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidget.id, null);
250                                 if (widget == null || widget.getId() == null) {
251                                         // Widget not found
252                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
253                                         return fieldsValidator;
254                                 }
255                                 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
256                         }
257                         if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
258                                 this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
259                         }
260                 }
261                 return fieldsValidator;
262         }
263
264         @Override
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)) {
269                         }
270                         FieldsValidator fieldsValidator = new FieldsValidator();
271                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
272                         return fieldsValidator;
273                 }
274                 return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget);
275         }
276
277         @Override
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);
285                                 } else {
286                                         boolean result = false;
287                                         Session localSession = null;
288                                         Transaction transaction = null;
289                                         try {
290                                                 localSession = sessionFactory.openSession();
291                                                 transaction = localSession.beginTransaction();
292                                                 localSession.delete(localSession.get(Widget.class, onboardingWidgetId));
293                                                 transaction.commit();
294                                                 result = true;
295                                         } catch (Exception e) {
296                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
297                                                 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingWidget rollback, exception = " + e);
298                                         } finally {
299                                                 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingWidget");
300                                         }
301                                         if (!result) {
302                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
303                                         }
304                                 }
305                         }
306                 }
307                 return fieldsValidator;
308         }
309
310 }