Update license; improve coverage; add docs dir
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / WidgetServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 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.openecomp.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.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.context.annotation.EnableAspectJAutoProxy;
51 import org.springframework.stereotype.Service;
52 import org.springframework.transaction.annotation.Transactional;
53
54 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
55 import org.openecomp.portalsdk.core.service.DataAccessService;
56 import org.openecomp.portalsdk.core.util.SystemProperties;
57 import org.openecomp.portalapp.portal.domain.EPUser;
58 import org.openecomp.portalapp.portal.domain.EPUserApp;
59 import org.openecomp.portalapp.portal.domain.Widget;
60 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
61 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
62 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
63 import org.openecomp.portalapp.portal.transport.FieldsValidator;
64 import org.openecomp.portalapp.portal.transport.OnboardingWidget;
65 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
66 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
67
68 @Service("widgetService")
69 @Transactional
70 @org.springframework.context.annotation.Configuration
71 @EnableAspectJAutoProxy
72 @EPMetricsLog
73 public class WidgetServiceImpl implements WidgetService {
74
75         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetServiceImpl.class);
76
77         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"
78                         + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
79
80         private String validAppsFilter = "";
81
82         private Long LONG_ECOMP_APP_ID = 1L;
83         private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
84         private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
85
86         private static final String urlField = "url";
87
88         private static final String nameField = "name";
89         @Autowired
90         AdminRolesService adminRolesService;
91         @Autowired
92         private SessionFactory sessionFactory;
93         @Autowired
94         private DataAccessService dataAccessService;
95
96         @PostConstruct
97         private void init() {
98                 try {
99                         validAppsFilter = " AND app.ENABLED = 'Y' AND app.APP_ID != " + SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
100                         ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
101                         LONG_ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
102                 } catch(Exception e) {
103                         logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
104                 }
105         }
106         
107         private String sqlWidgetsForAllApps() {
108                 return "SELECT" + baseSqlToken + validAppsFilter;
109         }
110
111         private String sqlWidgetsForAllAppsWhereUserIsAdmin(Long userId) {
112                 return "SELECT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + userId
113                                 + " AND FN_USER_ROLE.ROLE_ID = " + ACCOUNT_ADMIN_ROLE_ID + validAppsFilter;
114         }
115
116         private String sqlWidgetsForAllAppsWhereUserHasAnyRole(Long userId) {
117                 return "SELECT DISTINCT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
118                                 + userId + validAppsFilter;
119         }
120
121         @SuppressWarnings("unchecked")
122         @Override
123         public List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed) {
124                 List<OnboardingWidget> onboardingWidgets = new ArrayList<OnboardingWidget>();
125                 String sql = null;
126                 if (adminRolesService.isSuperAdmin(user)) {
127                         sql = this.sqlWidgetsForAllApps();
128                 } else if (managed) {
129                         if (adminRolesService.isAccountAdmin(user)) {
130                                 sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId());
131                         }
132                 } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
133                         sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId());
134                 }
135                 if (sql != null) {
136                         onboardingWidgets = dataAccessService.executeSQLQuery(sql, OnboardingWidget.class, null);
137                 }
138                 return onboardingWidgets;
139         }
140
141         private static final Object syncRests = new Object();
142
143         private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
144                 if (!superAdmin) {
145                         @SuppressWarnings("unchecked")
146                         List<EPUserApp> userRoles = dataAccessService.getList(EPUserApp.class,
147                                         " where userId = " + userId + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID + " and app.id = " + appId, null, null);
148                         return (userRoles.size() > 0);
149                 }
150                 return true;
151         }
152
153         private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
154                 @SuppressWarnings("unchecked")
155                 List<Widget> widgets = dataAccessService.getList(Widget.class,
156                                 " where url = '" + onboardingWidget.url + "'" + " or name = '" + onboardingWidget.name + "'", null, null);
157                 boolean dublicatedUrl = false;
158                 boolean dublicatedName = false;
159                 for (Widget widget : widgets) {
160                         if (onboardingWidget.id != null && onboardingWidget.id.equals(widget.getId())) {
161                                 // widget should not be compared with itself
162                                 continue;
163                         }
164                         if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.url)) {
165                                 dublicatedUrl = true;
166                                 if (dublicatedName) {
167                                         break;
168                                 }
169                         }
170                         if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.name) && widget.getAppId().equals(onboardingWidget.appId)) {
171                                 dublicatedName = true;
172                                 if (dublicatedUrl) {
173                                         break;
174                                 }
175                         }
176                 }
177                 if (dublicatedUrl || dublicatedName) {
178                         if (dublicatedUrl) {
179                                 fieldsValidator.addProblematicFieldName(urlField);
180                         }
181                         if (dublicatedName) {
182                                 fieldsValidator.addProblematicFieldName(nameField);
183                         }
184                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
185                         fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR;
186                 }
187         }
188
189         private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
190                 boolean result = false;
191                 Session localSession = null;
192                 Transaction transaction = null;
193                 try {
194                         localSession = sessionFactory.openSession();
195                         transaction = localSession.beginTransaction();
196                         Widget widget;
197                         if (onboardingWidget.id == null) {
198                                 widget = new Widget();
199                         } else {
200                                 widget = (Widget) localSession.get(Widget.class, onboardingWidget.id);
201                         }
202                         widget.setAppId(onboardingWidget.appId);
203                         widget.setName(onboardingWidget.name);
204                         widget.setWidth(onboardingWidget.width);
205                         widget.setHeight(onboardingWidget.height);
206                         widget.setUrl(onboardingWidget.url);
207                         localSession.saveOrUpdate(widget);
208                         transaction.commit();
209                         result = true;
210                 } catch (Exception e) {
211                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
212                         EcompPortalUtils.rollbackTransaction(transaction, "applyOnboardingWidget rollback, exception = " + e);
213                 } finally {
214                         EcompPortalUtils.closeLocalSession(localSession, "applyOnboardingWidget");
215                 }
216                 if (!result) {
217                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
218                 }
219         }
220
221         private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
222                 FieldsValidator fieldsValidator = new FieldsValidator();
223                 if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.appId)) {
224                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
225                         return fieldsValidator;
226                 }
227                 synchronized (syncRests) {
228                         // onboardingWidget.id is null for POST and not null for PUT
229                         if (onboardingWidget.id == null) {
230                                 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
231                         } else {
232                                 Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidget.id, null);
233                                 if (widget == null || widget.getId() == null) {
234                                         // Widget not found
235                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
236                                         return fieldsValidator;
237                                 }
238                                 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
239                         }
240                         if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
241                                 this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
242                         }
243                 }
244                 return fieldsValidator;
245         }
246
247         @Override
248         public FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget) {
249                 if (onboardingWidget.name.length() == 0 || onboardingWidget.url.length() == 0 || onboardingWidget.appId == null
250                                 || onboardingWidget.appId.equals(LONG_ECOMP_APP_ID) || onboardingWidget.width.intValue() <= 0 || onboardingWidget.height.intValue() <= 0) {
251                         if (onboardingWidget.appId.equals(LONG_ECOMP_APP_ID)) {
252                                 // logger.error("Alarm!!! Security breach attempt on user " + user.getFullName() + ", userId = " + user.getUserId());
253                         }
254                         FieldsValidator fieldsValidator = new FieldsValidator();
255                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
256                         return fieldsValidator;
257                 }
258                 return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget);
259         }
260
261         @Override
262         public FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId) {
263                 FieldsValidator fieldsValidator = new FieldsValidator();
264                 synchronized (syncRests) {
265                         Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidgetId, null);
266                         if (widget != null && widget.getId() != null) { // widget exists
267                                 if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(), widget.getAppId())) {
268                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
269                                 } else {
270                                         boolean result = false;
271                                         Session localSession = null;
272                                         Transaction transaction = null;
273                                         try {
274                                                 localSession = sessionFactory.openSession();
275                                                 transaction = localSession.beginTransaction();
276                                                 localSession.delete(localSession.get(Widget.class, onboardingWidgetId));
277                                                 transaction.commit();
278                                                 result = true;
279                                         } catch (Exception e) {
280                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
281                                                 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingWidget rollback, exception = " + e);
282                                         } finally {
283                                                 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingWidget");
284                                         }
285                                         if (!result) {
286                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
287                                         }
288                                 }
289                         }
290                 }
291                 return fieldsValidator;
292         }
293
294 }