nexus site path corrected
[portal.git] / ecomp-portal-BE / src / main / java / org / openecomp / portalapp / portal / service / WidgetServiceImpl.java
1 /*-
2  * ================================================================================
3  * eCOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.service;
21
22 import java.util.ArrayList;
23 import java.util.List;
24
25 import javax.annotation.PostConstruct;
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.hibernate.Session;
29 import org.hibernate.SessionFactory;
30 import org.hibernate.Transaction;
31 import org.openecomp.portalapp.portal.domain.EPUser;
32 import org.openecomp.portalapp.portal.domain.EPUserApp;
33 import org.openecomp.portalapp.portal.domain.Widget;
34 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
35 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
36 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
37 import org.openecomp.portalapp.portal.transport.FieldsValidator;
38 import org.openecomp.portalapp.portal.transport.OnboardingWidget;
39 import org.openecomp.portalapp.portal.utils.EPSystemProperties;
40 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
41 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
42 import org.openecomp.portalsdk.core.service.DataAccessService;
43 import org.openecomp.portalsdk.core.util.SystemProperties;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.context.annotation.EnableAspectJAutoProxy;
46 import org.springframework.stereotype.Service;
47 import org.springframework.transaction.annotation.Transactional;
48
49 @Service("widgetService")
50 @Transactional
51 @org.springframework.context.annotation.Configuration
52 @EnableAspectJAutoProxy
53 @EPMetricsLog
54 public class WidgetServiceImpl implements WidgetService {
55
56         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"
57                         + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
58
59         private String validAppsFilter = "";
60
61         private Long LONG_ECOMP_APP_ID = 1L;
62         private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
63         private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(EPSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
64
65         private static final String urlField = "url";
66
67         private static final String nameField = "name";
68         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetServiceImpl.class);
69
70         @Autowired
71         AdminRolesService adminRolesService;
72         @Autowired
73         private SessionFactory sessionFactory;
74         @Autowired
75         private DataAccessService dataAccessService;
76
77         @PostConstruct
78         private void init() {
79                 try {
80                         validAppsFilter = " AND app.ENABLED = 'Y' AND app.APP_ID != " + SystemProperties.getProperty(EPSystemProperties.ECOMP_APP_ID);
81                         ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
82                         LONG_ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ECOMP_APP_ID));
83                 } catch(Exception e) {
84                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
85                 }
86         }
87         
88         private String sqlWidgetsForAllApps() {
89                 return "SELECT" + baseSqlToken + validAppsFilter;
90         }
91
92         private String sqlWidgetsForAllAppsWhereUserIsAdmin(Long userId) {
93                 return "SELECT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + userId
94                                 + " AND FN_USER_ROLE.ROLE_ID = " + ACCOUNT_ADMIN_ROLE_ID + validAppsFilter;
95         }
96
97         private String sqlWidgetsForAllAppsWhereUserHasAnyRole(Long userId) {
98                 return "SELECT DISTINCT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
99                                 + userId + validAppsFilter;
100         }
101
102         @SuppressWarnings("unchecked")
103         @Override
104         public List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed) {
105                 List<OnboardingWidget> onboardingWidgets = new ArrayList<OnboardingWidget>();
106                 String sql = null;
107                 if (adminRolesService.isSuperAdmin(user)) {
108                         sql = this.sqlWidgetsForAllApps();
109                 } else if (managed) {
110                         if (adminRolesService.isAccountAdmin(user)) {
111                                 sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId());
112                         }
113                 } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
114                         sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId());
115                 }
116                 if (sql != null) {
117                         onboardingWidgets = dataAccessService.executeSQLQuery(sql, OnboardingWidget.class, null);
118                 }
119                 return onboardingWidgets;
120         }
121
122         private static final Object syncRests = new Object();
123
124         private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
125                 if (!superAdmin) {
126                         @SuppressWarnings("unchecked")
127                         List<EPUserApp> userRoles = dataAccessService.getList(EPUserApp.class,
128                                         " where id = " + userId + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID + " and app.id = " + appId, null, null);
129                         return (userRoles.size() > 0);
130                 }
131                 return true;
132         }
133
134         private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
135                 @SuppressWarnings("unchecked")
136                 List<Widget> widgets = dataAccessService.getList(Widget.class,
137                                 " where url = '" + onboardingWidget.url + "'" + " or name = '" + onboardingWidget.name + "'", null, null);
138                 boolean dublicatedUrl = false;
139                 boolean dublicatedName = false;
140                 for (Widget widget : widgets) {
141                         if (onboardingWidget.id != null && onboardingWidget.id.equals(widget.getId())) {
142                                 // widget should not be compared with itself
143                                 continue;
144                         }
145                         if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.url)) {
146                                 dublicatedUrl = true;
147                                 if (dublicatedName) {
148                                         break;
149                                 }
150                         }
151                         if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.name) && widget.getAppId().equals(onboardingWidget.appId)) {
152                                 dublicatedName = true;
153                                 if (dublicatedUrl) {
154                                         break;
155                                 }
156                         }
157                 }
158                 if (dublicatedUrl || dublicatedName) {
159                         if (dublicatedUrl) {
160                                 fieldsValidator.addProblematicFieldName(urlField);
161                         }
162                         if (dublicatedName) {
163                                 fieldsValidator.addProblematicFieldName(nameField);
164                         }
165                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
166                         fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR;
167                 }
168         }
169
170         private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
171                 boolean result = false;
172                 Session localSession = null;
173                 Transaction transaction = null;
174                 try {
175                         localSession = sessionFactory.openSession();
176                         transaction = localSession.beginTransaction();
177                         Widget widget;
178                         if (onboardingWidget.id == null) {
179                                 widget = new Widget();
180                         } else {
181                                 widget = (Widget) localSession.get(Widget.class, onboardingWidget.id);
182                         }
183                         widget.setAppId(onboardingWidget.appId);
184                         widget.setName(onboardingWidget.name);
185                         widget.setWidth(onboardingWidget.width);
186                         widget.setHeight(onboardingWidget.height);
187                         widget.setUrl(onboardingWidget.url);
188                         localSession.saveOrUpdate(widget);
189                         transaction.commit();
190                         result = true;
191                 } catch (Exception e) {
192                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
193                         EcompPortalUtils.rollbackTransaction(transaction, "applyOnboardingWidget rollback, exception = " + e);
194                 } finally {
195                         EcompPortalUtils.closeLocalSession(localSession, "applyOnboardingWidget");
196                 }
197                 if (!result) {
198                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
199                 }
200         }
201
202         private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
203                 FieldsValidator fieldsValidator = new FieldsValidator();
204                 if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.appId)) {
205                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
206                         return fieldsValidator;
207                 }
208                 synchronized (syncRests) {
209                         // onboardingWidget.id is null for POST and not null for PUT
210                         if (onboardingWidget.id == null) {
211                                 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
212                         } else {
213                                 Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidget.id, null);
214                                 if (widget == null || widget.getId() == null) {
215                                         // Widget not found
216                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
217                                         return fieldsValidator;
218                                 }
219                                 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
220                         }
221                         if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
222                                 this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
223                         }
224                 }
225                 return fieldsValidator;
226         }
227
228         @Override
229         public FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget) {
230                 if (onboardingWidget.name.length() == 0 || onboardingWidget.url.length() == 0 || onboardingWidget.appId == null
231                                 || onboardingWidget.appId.equals(LONG_ECOMP_APP_ID) || onboardingWidget.width.intValue() <= 0 || onboardingWidget.height.intValue() <= 0) {
232                         if (onboardingWidget.appId.equals(LONG_ECOMP_APP_ID)) {
233                                 // logger.error("Alarm!!! Security breach attempt on user " + user.getFullName() + ", userId = " + user.getUserId());
234                         }
235                         FieldsValidator fieldsValidator = new FieldsValidator();
236                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
237                         return fieldsValidator;
238                 }
239                 return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget);
240         }
241
242         @Override
243         public FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId) {
244                 FieldsValidator fieldsValidator = new FieldsValidator();
245                 synchronized (syncRests) {
246                         Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidgetId, null);
247                         if (widget != null && widget.getId() != null) { // widget exists
248                                 if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(), widget.getAppId())) {
249                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
250                                 } else {
251                                         boolean result = false;
252                                         Session localSession = null;
253                                         Transaction transaction = null;
254                                         try {
255                                                 localSession = sessionFactory.openSession();
256                                                 transaction = localSession.beginTransaction();
257                                                 localSession.delete(localSession.get(Widget.class, onboardingWidgetId));
258                                                 transaction.commit();
259                                                 result = true;
260                                         } catch (Exception e) {
261                                                 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
262                                                 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingWidget rollback, exception = " + e);
263                                         } finally {
264                                                 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingWidget");
265                                         }
266                                         if (!result) {
267                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
268                                         }
269                                 }
270                         }
271                 }
272                 return fieldsValidator;
273         }
274
275 }