Security/ Package Name changes
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / EPAppCommonServiceImpl.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.io.IOException;
41 import java.security.GeneralSecurityException;
42 import java.util.ArrayList;
43 import java.util.Base64;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.LinkedList;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Set;
50
51 import javax.annotation.PostConstruct;
52 import javax.servlet.http.HttpServletResponse;
53
54 import org.apache.commons.lang.StringUtils;
55 import org.hibernate.Session;
56 import org.hibernate.SessionFactory;
57 import org.hibernate.Transaction;
58 import org.hibernate.criterion.Criterion;
59 import org.hibernate.criterion.Restrictions;
60 import org.onap.portalapp.portal.domain.AdminUserApp;
61 import org.onap.portalapp.portal.domain.AdminUserApplications;
62 import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel;
63 import org.onap.portalapp.portal.domain.AppsResponse;
64 import org.onap.portalapp.portal.domain.EPApp;
65 import org.onap.portalapp.portal.domain.EPUser;
66 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
67 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
68 import org.onap.portalapp.portal.domain.EPUserAppsManualSortPreference;
69 import org.onap.portalapp.portal.domain.EPUserAppsSortPreference;
70 import org.onap.portalapp.portal.domain.EPWidgetsManualSortPreference;
71 import org.onap.portalapp.portal.domain.EcompApp;
72 import org.onap.portalapp.portal.domain.UserRole;
73 import org.onap.portalapp.portal.domain.UserRoles;
74 import org.onap.portalapp.portal.ecomp.model.AppCatalogItem;
75 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
76 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
77 import org.onap.portalapp.portal.transport.EPAppsManualPreference;
78 import org.onap.portalapp.portal.transport.EPAppsSortPreference;
79 import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref;
80 import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
81 import org.onap.portalapp.portal.transport.FieldsValidator;
82 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
83 import org.onap.portalapp.portal.transport.LocalRole;
84 import org.onap.portalapp.portal.transport.OnboardingApp;
85 import org.onap.portalapp.portal.ueb.EPUebHelper;
86 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
87 import org.onap.portalapp.portal.utils.EcompPortalUtils;
88 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
89 import org.onap.portalsdk.core.onboarding.ueb.Helper;
90 import org.onap.portalsdk.core.onboarding.ueb.TopicManager;
91 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
92 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
93 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
94 import org.onap.portalsdk.core.service.DataAccessService;
95 import org.onap.portalsdk.core.util.SystemProperties;
96 import org.springframework.beans.factory.annotation.Autowired;
97
98 import com.att.nsa.apiClient.http.HttpException;
99 import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
100 import com.att.nsa.cambria.client.CambriaClientBuilders;
101 import com.att.nsa.cambria.client.CambriaIdentityManager;
102 import com.att.nsa.cambria.client.CambriaTopicManager;
103 import com.google.common.primitives.Ints;
104
105 public class EPAppCommonServiceImpl implements EPAppService {
106
107         protected String ECOMP_APP_ID = "1";
108         protected String SUPER_ADMIN_ROLE_ID = "1";
109         protected String ACCOUNT_ADMIN_ROLE_ID = "999";
110         protected String RESTRICTED_APP_ROLE_ID = "900";
111
112         private static final String urlField = "url";
113         private static final String nameField = "name";
114
115         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
116
117         @Autowired
118         private AdminRolesService adminRolesService;
119         @Autowired
120         protected SessionFactory sessionFactory;
121         @Autowired
122         private DataAccessService dataAccessService;
123         @Autowired
124         private EPUebHelper epUebHelper;        
125
126         @PostConstruct
127         private void init() {
128                 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
129                 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
130                 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
131                 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
132         }
133
134         @Override
135         public List<EPApp> getUserAsAdminApps(EPUser user) {
136                 if (adminRolesService.isAccountAdmin(user)) {
137                         String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
138                                         + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
139                                         + " AND FN_APP.ENABLED = 'Y'";
140                         logQuery(sql);
141                         try {
142                                 @SuppressWarnings("unchecked")
143                                 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
144                                 return adminApps;
145                         } catch (Exception e) {
146                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
147                                 return null;
148                         }
149                 } else {
150                         logger.error(EELFLoggerDelegate.errorLogger,
151                                         "getUserAsAdminApps: only Account Admin may invoke this function!");
152                         return new ArrayList<EPApp>();
153                 }
154         }
155
156         @Override
157         public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
158                 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
159                                 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
160                                 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
161                                 + " AND FN_APP.ENABLED = 'Y'";
162
163                 String sql = String.format(format, orgUserId);
164                 logQuery(sql);
165
166                 try {
167                         @SuppressWarnings("unchecked")
168                         List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
169                         return adminApps;
170                 } catch (Exception e) {
171                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
172                         return null;
173                 }
174         }
175
176         @Override
177         public List<EPApp> getAppsFullList() {
178                 @SuppressWarnings("unchecked")
179                 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
180                 return apps;
181         }
182
183         @Override
184         public List<EcompApp> getEcompAppAppsFullList() {
185                 return transformAppsToEcompApps(getAppsFullList());
186         }
187
188         @Override
189         public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
190                 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
191                 for (EPApp app : appsList) {
192                         EcompApp ecompApp = new EcompApp();
193                         ecompApp.setId(app.getId());
194                         ecompApp.setName(app.getName());
195                         ecompApp.setImageUrl(app.getImageUrl());
196                         ecompApp.setDescription(app.getDescription());
197                         ecompApp.setNotes(app.getNotes());
198                         ecompApp.setUrl(app.getUrl());
199                         ecompApp.setAlternateUrl(app.getAlternateUrl());
200                         ecompApp.setUebTopicName(app.getUebTopicName());
201                         ecompApp.setUebKey(app.getUebKey());
202                         ecompApp.setUebSecret(app.getUebSecret());
203                         ecompApp.setEnabled(app.getEnabled());
204                         ecompApp.setCentralAuth(app.getCentralAuth());
205                         ecompApp.setNameSpace(app.getNameSpace());
206                         ecompApp.setRestrictedApp(app.isRestrictedApp());
207                         ecompAppList.add(ecompApp);
208                 }
209                 return ecompAppList;
210         }
211
212         @Override
213         public EPApp getApp(Long appId) {
214                 try {
215                         return (EPApp) dataAccessService.getDomainObject(EPApp.class, appId, null);
216                 } catch (Exception e) {
217                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
218                         return null;
219                 }
220         }
221
222         @SuppressWarnings("unchecked")
223         @Override
224         public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
225                 if (adminRolesService.isAccountAdmin(user)) {
226                         String format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
227                                         + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
228                                         + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
229                         String sql = String.format(format, user.getId());
230                         // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
231                         // app.APP_REST_ENDPOINT <> ''";
232                         logQuery(sql);
233                         try {
234                                 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
235                         } catch (Exception e) {
236                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
237                                 logger.error(EELFLoggerDelegate.errorLogger,
238                                                 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
239                         }
240                 }
241                 return new ArrayList<AppIdAndNameTransportModel>();
242         }
243
244         @Override
245         public EPApp getAppDetail(String appName) {
246                 final Map<String, String> params = new HashMap<String, String>();
247                 try {
248                         params.put("appName", appName);
249                         @SuppressWarnings("unchecked")
250                         List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
251                         return (apps.size() > 0) ? apps.get(0) : null;
252                 } catch(Exception e) {
253                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
254                         return null;
255                 }
256         }
257         
258         @Override
259         public EPApp getAppDetailByAppName(String appName) {
260                 final Map<String, String> params = new HashMap<String, String>();
261                 try {
262                         params.put("appName", appName);
263                         @SuppressWarnings("unchecked")
264                         List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getAppDetailsByAppName", params, null);
265                         if (apps.size() > 0) {
266                                 EPApp app = apps.get(0);
267                                 if (!EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
268                                         app.setCentralAuth(false);
269                                 }
270                                 return app;
271                         } else{
272                                 return null;
273                         }
274                 } catch (Exception e) {
275                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
276                         return null;
277                 }
278         }
279
280         @SuppressWarnings("unchecked")
281         @Override
282         public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
283                 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
284                         String format = "";
285                         String sql = "";
286                         if (adminRolesService.isSuperAdmin(user)) {
287                                 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
288                                                 + "where app.ENABLED = 'Y' AND app.app_type = 1";
289                         } else {
290                                 format = "SELECT app.APP_ID, app.APP_NAME, APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
291                                                 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
292                                                 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
293                         }
294                         sql = String.format(format, user.getId());
295                         // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
296                         // app.APP_REST_ENDPOINT <> ''";
297                         logQuery(sql);
298                         try {
299                                 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
300                         } catch (Exception e) {
301                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
302                                 logger.error(EELFLoggerDelegate.errorLogger,
303                                                 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
304                         }
305                 }
306                 return new ArrayList<AppIdAndNameTransportModel>();
307         }
308
309         protected void logQuery(String sql) {
310                 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
311         }
312
313         public DataAccessService getDataAccessService() {
314                 return dataAccessService;
315         }
316
317         public void setDataAccessService(DataAccessService dataAccessService) {
318                 this.dataAccessService = dataAccessService;
319         }
320
321         @SuppressWarnings("unchecked")
322         @Override
323         public List<AdminUserApplications> getAppsAdmins() {
324                 try {
325                         Map<String, String> params = new HashMap<>();
326                         params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
327                         List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
328                                         params, null);
329                         return aggregateRowsResultsByUserId(adminApps);
330                 } catch (Exception e) {
331                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
332                         return null;
333                 }
334         }
335
336         private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
337                 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
338                 for (AdminUserApp app : adminApps) {
339                         Long userId = app.getUser_Id();
340                         if (adminUserApplications.get(userId) == null)
341                                 adminUserApplications.put(userId, new AdminUserApplications(app));
342                         else
343                                 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
344                 }
345                 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
346         }
347
348         @Override
349         public List<AppsResponse> getAllApps(Boolean all) {
350                 // If all is true, return both active and inactive apps. Otherwise, just
351                 // active apps.
352                 @SuppressWarnings("unchecked")
353                 // Sort the list by application name so the drop-down looks pretty.
354                 List<EPApp> apps = all
355                                 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
356                                 : (List<EPApp>) dataAccessService.getList(EPApp.class,
357                                                 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
358
359                 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
360                 for (EPApp app : apps) {
361                         appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
362                 }
363                 return appsModified;
364         }
365
366         @Override
367         public UserRoles getUserProfile(String loginId) {
368                 final Map<String, String> params = new HashMap<>();
369                 params.put("org_user_id", loginId);
370                 @SuppressWarnings("unchecked")
371                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
372                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
373                 if (usersRolesList == null || usersRolesList.size() < 1)
374                         return null;
375
376                 return usersRolesList.get(0);
377         }
378
379         @Override
380         public UserRoles getUserProfileNormalized(EPUser user) {
381                 // Check database.
382                 UserRoles userAndRoles = getUserProfile(user.getLoginId());
383                 // If no roles are defined, treat this user as a guest.
384                 if (user.isGuest() || userAndRoles == null) {
385                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
386                                         user.getLoginId());
387                         UserRole userRole = new UserRole();
388                         userRole.setUser_Id(user.getId());
389                         userRole.setOrgUserId(user.getLoginId());
390                         userRole.setFirstName(user.getFirstName());
391                         userRole.setLastName(user.getLastName());
392                         userRole.setRoleId(-1L);
393                         userRole.setRoleName("Guest");
394                         userRole.setUser_Id(-1L);
395                         userAndRoles = new UserRoles(userRole);
396                 }
397
398                 return userAndRoles;
399         }
400
401         protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
402                 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
403                 for (UserRole user : userRoleList) {
404                         String orgUserId = user.getOrgUserId();
405                         if (userRoles.get(orgUserId) == null)
406                                 userRoles.put(orgUserId, new UserRoles(user));
407                         else
408                                 userRoles.get(orgUserId).addRole(user.getRoleName());
409                 }
410                 return new ArrayList<UserRoles>(userRoles.values());
411         }
412
413         private boolean isRestrictedApp(Long appId) {
414                 EPApp app = getApp(appId);
415                 return app.isRestrictedApp();
416         }
417
418         // For the functional menu edit
419         @Override
420         public List<LocalRole> getAppRoles(Long appId) {
421                 String sql = "";
422                 if (isRestrictedApp(appId)) {
423                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
424                 }else if(appId == 1){
425                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
426                 }else{
427                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
428                 }
429                 logQuery(sql);
430                 @SuppressWarnings("unchecked")
431                 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
432                 return appRoles;
433         }
434
435         protected String userAppsQuery(EPUser user) {
436                 StringBuilder query = new StringBuilder();
437                 if (adminRolesService.isSuperAdmin(user)) {
438                         query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
439                 } else {
440                         query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
441                         query.append(
442                                         "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
443                         query.append(" AND FN_APP.ENABLED = 'Y'");
444                 }
445                 return query.toString();
446         }
447
448         protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
449                 FieldsValidator fieldsValidator = new FieldsValidator();
450                 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
451                                 || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
452                                 || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
453                                 || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID))
454                                 // For a normal app (appType==1), these fields must be filled
455                                 // in.
456                                 // For a restricted app (appType==2), they will be empty.
457                                 || ((!onboardingApp.restrictedApp)
458                                                 && (onboardingApp.username == null || onboardingApp.username.length() == 0
459                                                                 || onboardingApp.appPassword == null || onboardingApp.appPassword.length() == 0))) {
460                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
461                 }
462                 return fieldsValidator;
463         }
464
465         @Override
466         public List<EPApp> getUserApps(EPUser user) {
467                 List<EPApp> openApps = getOpenApps();
468
469                 if (user.isGuest()) {
470                         return openApps;
471                 } else {
472                         String sql = userAppsQuery(user);
473                         logQuery(sql);
474
475                         // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
476                         List<EPApp> appsList = new ArrayList<>();
477                         @SuppressWarnings("unchecked")
478                         List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
479                         HashSet<EPApp> appSet = new HashSet<>();
480                         for (EPApp app : adminApps) {
481                                 appSet.add(app);
482                                 appsList.add(app);
483                         }
484
485                         for (EPApp app : openApps) {
486                                 if (!appSet.contains(app))
487                                         appsList.add(app);
488                         }
489
490                         return appsList;
491                 }
492         }
493
494         @Override
495         public List<EPApp> getPersAdminApps(EPUser user) {
496                 final Map<String, Long> params = new HashMap<>();
497                 params.put("userId", user.getId());
498                 // Named query is stored in EP.hbm.xml, mapped to EPApp
499                 @SuppressWarnings("unchecked")
500                 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
501                 return list;
502         }
503
504         @Override
505         public List<EPApp> getPersUserApps(EPUser user) {
506                 final Map<String, Long> params = new HashMap<>();
507                 params.put("userId", user.getId());
508                 // Named query is stored in EP.hbm.xml, mapped to EPApp
509                 @SuppressWarnings("unchecked")
510                 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
511                 return list;
512         }
513
514         /*
515          * (non-Javadoc)
516          *
517          * @see
518          * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog(
519          * org.openecomp.portalapp.portal.domain.EPUser)
520          */
521         @Override
522         public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
523                 final Map<String, Long> params = new HashMap<>();
524                 params.put("userId", user.getId());
525                 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
526                 @SuppressWarnings("unchecked")
527                 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
528                 return list;
529         }
530
531         /*
532          * (non-Javadoc)
533          *
534          * @see
535          * org.openecomp.portalapp.portal.service.EPAppService#getAdminAppCatalog(
536          * org.openecomp.portalapp.portal.domain.EPUser)
537          */
538         @Override
539         public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
540                 final Map<String, Long> params = new HashMap<>();
541                 params.put("userId", user.getId());
542                 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
543                 @SuppressWarnings("unchecked")
544                 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
545                 return list;
546         }
547
548         private List<EPApp> getOpenApps() {
549                 @SuppressWarnings("unchecked")
550                 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
551                 return openApps;
552         }
553
554         @SuppressWarnings("unchecked")
555         @Override
556         public List<EPApp> getAppsOrderByName(EPUser user) {
557                 final Map<String, Long> params = new HashMap<>();
558                 List<EPApp> sortedAppsByName = null;
559                 try {
560                         if (adminRolesService.isSuperAdmin(user)) {
561                                 params.put("userId", user.getId());
562                                 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
563                         } else {
564                                 params.put("userId", user.getId());
565                                 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
566                         }
567                 } catch (Exception e) {
568                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
569                 }
570                 return sortedAppsByName;
571         }
572
573         @SuppressWarnings("unchecked")
574         @Override
575         public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
576
577                 final Map<String, Long> params = new HashMap<>();
578                 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
579                 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
580                 try {
581                         if (adminRolesService.isSuperAdmin(user)) {
582                                 params.put("userId", user.getId());
583                                 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
584                         } else {
585                                 params.put("userId", user.getId());
586                                 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
587                         }
588                         Set<String> epAppSet = new HashSet<String>();
589                         for (EPApp eapp : sortedAppsByLastUsed)
590                                 if (!epAppSet.contains(eapp.getName())) {
591                                         finalsortedAppsByLastUsed.add(eapp);
592                                         epAppSet.add(eapp.getName());
593                                 }
594
595                 } catch (Exception e) {
596                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
597                 }
598                 return finalsortedAppsByLastUsed;
599         }
600
601         @SuppressWarnings("unchecked")
602         @Override
603         public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
604                 final Map<String, Long> params = new HashMap<>();
605                 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
606                 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
607                 try {
608                         if (adminRolesService.isSuperAdmin(user)) {
609                                 params.put("userId", user.getId());
610                                 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
611                         } else {
612                                 params.put("userId", user.getId());
613                                 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
614                         }
615                         Set<String> epAppSet = new HashSet<String>();
616
617                         for (EPApp eapp : sortedAppsByMostUsed) {
618                                 if (!epAppSet.contains(eapp.getName())) {
619                                         finalsortedAppsByMostUsed.add(eapp);
620                                         epAppSet.add(eapp.getName());
621                                 }
622                         }
623                 } catch (Exception e) {
624                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
625                 }
626
627                 return finalsortedAppsByMostUsed;
628         }
629
630         /*
631          * This Method retrieves the User Apps by Sort Manual Preference
632          *
633          * @param: user--contains LoggedIn User Data
634          */
635         @SuppressWarnings("unchecked")
636         @Override
637         public List<EPApp> getAppsOrderByManual(EPUser user) {
638                 final Map<String, Long> params = new HashMap<>();
639                 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
640                 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
641                 try {
642                         if (adminRolesService.isSuperAdmin(user)) {
643                                 params.put("userId", user.getId());
644                                 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
645                         } else {
646                                 params.put("userId", user.getId());
647                                 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
648                         }
649                         Set<String> epAppSet = new HashSet<String>();
650
651                         for (EPApp eapp : sortedAppsByManual) {
652                                 if (!epAppSet.contains(eapp.getName())) {
653                                         finalsortedAppsByManual.add(eapp);
654                                         epAppSet.add(eapp.getName());
655                                 }
656                         }
657                 } catch (Exception e) {
658                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
659                 }
660                 return finalsortedAppsByManual;
661         }
662
663         @Override
664         public List<OnboardingApp> getOnboardingApps() {
665                 @SuppressWarnings("unchecked")
666                 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
667                 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
668                 for (EPApp app : apps) {
669                         OnboardingApp onboardingApp = new OnboardingApp();
670                         createOnboardingFromApp(app, onboardingApp);
671                         onboardingAppsList.add(onboardingApp);
672                 }
673                 return onboardingAppsList;
674         }
675
676         @Override
677         public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
678                 @SuppressWarnings("unchecked")
679                 List<EPApp> apps = dataAccessService.getList(EPApp.class,
680                                 " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
681                 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
682                 for (EPApp app : apps) {
683                         OnboardingApp onboardingApp = new OnboardingApp();
684                         createOnboardingFromApp(app, onboardingApp);
685                         onboardingAppsList.add(onboardingApp);
686                 }
687                 return onboardingAppsList;
688         }
689
690         @SuppressWarnings("unchecked")
691         private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
692                 boolean duplicatedUrl = false;
693                 boolean duplicatedName = false;
694                 List<EPApp> apps;
695                 if (onboardingApp.id == null) {
696                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
697                         Criterion urlCrit =Restrictions.eq("url", onboardingApp.url);
698                         Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);                        
699                         Criterion orCrit = Restrictions.or(urlCrit, nameCrit);
700                         
701                         restrictionsList.add(orCrit);
702                         apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
703                         
704                         
705                 } else {
706                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
707                         Criterion idCrit =Restrictions.eq("id", onboardingApp.id);
708                         Criterion urlCrit =Restrictions.eq("url", onboardingApp.url);
709                         Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);                        
710                         Criterion orCrit = Restrictions.or(idCrit, urlCrit, nameCrit);
711                         
712                         restrictionsList.add(orCrit);
713                         apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
714                         
715                 }
716                 for (EPApp app : apps) {
717                         if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) {
718                                 continue;
719                         }
720                         if (!duplicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) {
721                                 duplicatedUrl = true;
722                                 if (duplicatedName) {
723                                         break;
724                                 }
725                         }
726                         if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
727                                 duplicatedName = true;
728                                 if (duplicatedUrl) {
729                                         break;
730                                 }
731                         }
732                 }
733                 if (duplicatedUrl || duplicatedName) {
734                         if (duplicatedUrl) {
735                                 fieldsValidator.addProblematicFieldName(urlField);
736                         }
737                         if (duplicatedName) {
738                                 fieldsValidator.addProblematicFieldName(nameField);
739                         }
740                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
741                         fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
742                 }
743         }
744
745         @Override
746         public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
747                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
748                 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
749                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
750                         validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
751                 }
752                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
753                         if (modifiedOnboardingApp.id != null) {
754                                 updateApp(modifiedOnboardingApp.id, modifiedOnboardingApp, fieldsValidator, user);
755                         } else {
756                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
757                         }
758                 }
759                 return fieldsValidator;
760         }
761
762         @Override
763         public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
764                 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
765                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
766                         validateOnboardingApp(newOnboardingApp, fieldsValidator);
767                 }
768                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
769                         if (newOnboardingApp.id == null) {
770                                 updateApp(null, newOnboardingApp, fieldsValidator, user);
771                         } else {
772                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
773                         }
774                 }
775                 return fieldsValidator;
776         }
777
778         @SuppressWarnings("unchecked")
779         @Override
780         public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
781                 FieldsValidator fieldsValidator = new FieldsValidator();
782                 if (!adminRolesService.isSuperAdmin(user)) {
783                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
784                         return fieldsValidator;
785                 }
786                 final Map<String, Long> params = new HashMap<>();
787                 params.put("app_id", appid);
788                 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
789                 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
790             for(int i=0;i<EPUserAppRolesRequestList.size();i++)
791             {
792              dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
793                 
794             }
795             Session localSession = null;
796                 Transaction transaction = null;
797                 Boolean result = false;
798                 try {
799                         localSession = sessionFactory.openSession();
800                         transaction = localSession.beginTransaction();
801                         
802                         // 1) Remove the URL for any functional menu item associated with
803                         // this app
804                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
805                         // Named query is stored in EP.hbm.xml, mapped to EPApp
806                          dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
807                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp:  Deleted URL for any functional menu item associated with app");
808
809                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
810                         // 2)Remove any favorites associated with a menu item that is
811                         // associated with this app
812                         dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
813                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
814
815                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
816                         // 3)Remove all role, appid records from fn_menu_functional_role
817                         // that are associated with this app
818                          dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
819                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
820
821                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
822                         // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
823                         // that are associated with this app
824                          dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
825                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
826                          
827                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
828                         // 5)Remove all rolefunctions, appid records from ep_app_function
829                         // that are associated with this app
830                          dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
831                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp:  Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
832          
833                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
834                         // 6)Remove all records from fn_user_role associated with this app
835                          dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
836                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
837                          
838                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
839                         // 7)Remove any widgets associated with this app
840                          dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
841                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
842                          
843                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
844                         // 8)Remove any roles associated with this app
845                          dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
846                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
847                          
848                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
849                         // 9)Remove all records from fn_role associated with this app
850                          dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
851                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
852                         
853                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
854                          // 10)Remove app contact us entries
855                          dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
856                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
857
858                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
859                         // 11)Remove rows in the app personalization selection table
860                          dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
861                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
862                          
863                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
864                         // 12)Remove rows in the app personalization sort table
865                          dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
866                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
867                          
868                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
869                         // 13)Remove rows in the app personalization sort table
870                          dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
871                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
872                          
873                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
874                         // 14)Remove rows in the ep_web_analytics_source
875                          dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
876                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
877                          
878                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
879                         // 15)Delete the app
880                          dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
881                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
882                         
883                         /*
884                         // 1) Remove the URL for any functional menu item associated with
885                         // this app
886                         String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
887                                         + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
888                         logQuery(sql);
889                         Query query = localSession.createSQLQuery(sql);
890                         query.executeUpdate();
891
892                         // Remove any favorites associated with a menu item that is
893                         // associated with this app
894                         sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
895                                         + " where fn_menu_functional_roles.app_id='" + appid + "' "
896                                         + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
897                         logQuery(sql);
898                         query = localSession.createSQLQuery(sql);
899                         query.executeUpdate();
900
901                         // Remove all role, appid records from fn_menu_functional_role
902                         // that are associated with this app
903                         sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
904                         logQuery(sql);
905                         query = localSession.createSQLQuery(sql);
906                         query.executeUpdate();
907                         
908                         
909                         // Remove all roles, rolefunctions, appid records from ep_app_role_function
910                         // that are associated with this app
911                     sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
912                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
913                          query = localSession.createSQLQuery(sql);
914                         query.executeUpdate();
915                         
916                         //Remove all rolefunctions, appid records from ep_app_function
917                         // that are associated with this app
918                         sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
919                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
920                         query = localSession.createSQLQuery(sql);
921                         query.executeUpdate();
922
923                         // Remove all records from fn_user_role associated with this app
924                         sql = "delete from fn_user_role where app_id='" + appid + "'";
925                         logQuery(sql);
926                         query = localSession.createSQLQuery(sql);
927                         query.executeUpdate();
928
929                         // Remove any widgets associated with this app
930                         sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
931                         logQuery(sql);
932                         query = localSession.createSQLQuery(sql);
933                         query.executeUpdate();
934
935                         // Remove any roles associated with this app
936                         sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
937                                         + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
938                         logQuery(sql);
939                         query = localSession.createSQLQuery(sql);
940                         query.executeUpdate();
941
942                         // Remove all records from fn_role associated with this app
943                         sql = "delete from fn_role where app_id='" + appid + "'";
944                         logQuery(sql);
945                         query = localSession.createSQLQuery(sql);
946                         query.executeUpdate();
947
948                         // Remove app contact us entries
949                         sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
950                         logQuery(sql);
951                         query = localSession.createSQLQuery(sql);
952                         query.executeUpdate();
953
954                         // Remove rows in the app personalization selection table
955                         sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
956                         logQuery(sql);
957                         query = localSession.createSQLQuery(sql);
958                         query.executeUpdate();
959
960                         // Remove rows in the app personalization sort table
961                         sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
962                         logQuery(sql);
963                         query = localSession.createSQLQuery(sql);
964                         query.executeUpdate();
965
966                         // Remove rows in the app personalization sort table
967                         sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
968                         logQuery(sql);
969                         query = localSession.createSQLQuery(sql);
970                         query.executeUpdate();
971
972                         // Remove rows in the app personalization sort table
973                         sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
974                         logQuery(sql);
975                         query = localSession.createSQLQuery(sql);
976                         query.executeUpdate();
977
978                         // Delete the app
979                         sql = "delete from fn_app where app_id='" + appid + "'";
980                         logQuery(sql);
981                         query = localSession.createSQLQuery(sql);
982                         query.executeUpdate();
983
984                         transaction.commit();
985                         */
986                         result = true;
987                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
988                 } catch (Exception e) {
989                         logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
990                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
991                         EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
992                 } finally {
993                         EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
994                 }
995                 if (!result) {
996                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
997                 }
998                 return fieldsValidator;
999         }
1000
1001         private static Object syncRests = new Object();
1002
1003         // An app has been enabled/disabled. Must enable/disable all associated
1004         // functional menu items.
1005         protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1006                 String active_yn = enabled ? "Y" : "N";
1007                 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1008                                 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1009                                 + " AND r.app_id = '" + appId + "' ";
1010                 logQuery(sql);
1011                 @SuppressWarnings("unchecked")
1012                 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1013                 for (FunctionalMenuItem menuItem : menuItems) {
1014                         FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1015                                         menuItem.menuId);
1016                         myMenuItem.active_yn = active_yn;
1017                         localSession.save(myMenuItem);
1018                 }
1019         }
1020
1021         // Attention! If (appId == null) we use this function to create application
1022         // otherwise we use it to modify existing application
1023         protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1024                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1025                 // Separate out the code for a restricted app, since it doesn't need any
1026                 // of the UEB code.
1027                 if (onboardingApp.restrictedApp) {
1028                         boolean result = false;
1029                         Session localSession = null;
1030                         Transaction transaction = null;
1031                         try {
1032                                 localSession = sessionFactory.openSession();
1033                                 transaction = localSession.beginTransaction();
1034                                 EPApp app;
1035                                 if (appId == null) {
1036                                         app = new EPApp();
1037                                 } else {
1038                                         app = (EPApp) localSession.get(EPApp.class, appId);
1039                                         if (app == null || app.getId() == null) { // App is already
1040                                                 // deleted!
1041                                                 transaction.commit();
1042                                                 localSession.close();
1043                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1044                                                 return;
1045                                         }
1046                                 }
1047                                 createAppFromOnboarding(app, onboardingApp, localSession);
1048                                 localSession.saveOrUpdate(app);
1049                                 // Enable or disable all menu items associated with this app
1050                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1051                                 transaction.commit();
1052                                 result = true;
1053                         } catch (Exception e) {
1054                                 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1055                                 EcompPortalUtils.rollbackTransaction(transaction,
1056                                                 "updateApp rollback, exception = " + e.toString());
1057                         } finally {
1058                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1059                         }
1060                         if (!result) {
1061                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1062                         }
1063
1064                 } else {
1065                         updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1066                         
1067                 }
1068         }
1069
1070         protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1071                         EPUser user) {
1072                 synchronized (syncRests) {
1073                         boolean result = false;
1074                         Session localSession = null;
1075                         Transaction transaction = null;
1076                         try {
1077                                 localSession = sessionFactory.openSession();
1078                                 transaction = localSession.beginTransaction();
1079                                 EPApp app;
1080                                 if (appId == null) {
1081                                         app = new EPApp();
1082                                         // -------------------------------------------------------------------------------------------
1083                                         // Register this App with the UEB communication server.
1084                                         // Save
1085                                         // the App's unique mailbox/topic
1086                                         // name and keys to the FN_APP table. The App's mailbox
1087                                         // and
1088                                         // keys will be visible to the
1089                                         // admin on the ECOMP portal.
1090                                         // -------------------------------------------------------------------------------------------
1091                                         TopicManager topicManager = new TopicManager() {
1092
1093                                                 EPAppCommonServiceImpl service;
1094
1095                                                 public void init(EPAppCommonServiceImpl _service) {
1096                                                         service = _service;
1097                                                 }
1098
1099                                                 public void createTopic(String key, String secret, String topicName,
1100                                                                 String topicDescription) throws HttpException, CambriaApiException, IOException {
1101
1102                                                         init(EPAppCommonServiceImpl.this);
1103                                                         final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1104                                                         if (logger.isInfoEnabled()) {
1105                                                                 logger.info("==> createTopic");
1106                                                                 logger.info("topicName: " + topicName);
1107                                                                 logger.info("topicDescription: " + topicDescription);
1108                                                         }
1109                                                         CambriaTopicManager tm = null;
1110                                                         try {
1111                                                                 tm = service.getTopicManager(urlList, key, secret);
1112                                                         } catch (Exception e) {
1113                                                                 logger.error("pub.build Exception ", e);
1114                                                                 throw new CambriaApiException(topicName);
1115                                                         }
1116                                                         tm.createTopic(topicName, topicDescription, 1, 1);
1117                                                 }
1118
1119                                                 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1120                                                                 String topicName) throws HttpException, CambriaApiException, IOException {
1121                                                         logger.info("==> addPublisher to topic " + topicName);
1122                                                         final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1123                                                         CambriaTopicManager tm = null;
1124                                                         try {
1125                                                                 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1126                                                         } catch (Exception e) {
1127                                                                 logger.error("pub.build Exception ", e);
1128                                                                 throw new CambriaApiException(topicName);
1129                                                         }
1130                                                         tm.allowProducer(topicName, publisherKey);
1131                                                 }
1132
1133                                         };
1134                                         final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1135                                                         .usingHosts(Helper.uebUrlList()).build();
1136                                         com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1137                                                         "ECOMP Portal Owner");
1138                                         String appKey = credential.getApiKey();
1139                                         String appSecret = credential.getApiSecret();
1140                                         String appMailboxName = null;
1141
1142                                         int maxNumAttemptsToCreateATopic = 3;
1143                                         boolean successfullyCreatedMailbox = false;
1144                                         for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1145                                                 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1146
1147                                                 try {
1148                                                         topicManager.createTopic(
1149                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1150                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1151                                                                         appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
1152                                                         successfullyCreatedMailbox = true;
1153                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1154                                                                         "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
1155                                                         logger.debug(EELFLoggerDelegate.debugLogger, "    Key = " + appKey + " Secret = "
1156                                                                         + appSecret + " generated using = " + user.getEmail());
1157                                                         break;
1158                                                 } catch (HttpException e) {
1159                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1160                                                         if (e.getStatusCode() == 409) {
1161                                                                 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1162                                                                                 + " already exists. Will try using a different name", e);
1163                                                         } else {
1164                                                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1165                                                                                 e);
1166                                                         }
1167                                                 }
1168                                         }
1169
1170                                         if (successfullyCreatedMailbox) {
1171                                                 onboardingApp.setUebTopicName(appMailboxName);
1172                                                 onboardingApp.setUebKey(appKey);
1173                                                 onboardingApp.setUebSecret(appSecret);
1174
1175                                                 try {
1176                                                         /*
1177                                                          * EP is a publisher to this App's new mailbox
1178                                                          */
1179                                                         topicManager.addPublisher(
1180                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1181                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1182                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1183                                                                         appMailboxName);
1184
1185                                                         /*
1186                                                          * This App is a subscriber of its own mailbox
1187                                                          */
1188                                                         topicManager.addSubscriber(
1189                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1190                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1191                                                                         appMailboxName);
1192
1193                                                         /*
1194                                                          * This App is a publisher to EP
1195                                                          */
1196                                                         topicManager.addPublisher(
1197                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1198                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1199                                                                         PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1200                                                 } catch (HttpException | CambriaApiException | IOException e) {
1201                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1202                                                         logger.error(EELFLoggerDelegate.errorLogger,
1203                                                                         "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1204                                                         transaction.commit();
1205                                                         localSession.close();
1206                                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1207                                                         return;
1208                                                 }
1209                                         } else {
1210                                                 transaction.commit();
1211                                                 localSession.close();
1212                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1213                                                 return;
1214                                         }
1215                                 } else {
1216                                         app = (EPApp) localSession.get(EPApp.class, appId);
1217                                         if (app == null || app.getId() == null) {
1218                                                 // App is already deleted!
1219                                                 transaction.commit();
1220                                                 localSession.close();
1221                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1222                                                 return;
1223                                         }
1224                                 }
1225                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1226                                 createAppFromOnboarding(app, onboardingApp, localSession);
1227                                 logger.debug(EELFLoggerDelegate.debugLogger,
1228                                                 "LR: updateApp: finished calling createAppFromOnboarding");
1229                                 localSession.saveOrUpdate(app);
1230                                 logger.debug(EELFLoggerDelegate.debugLogger,
1231                                                 "LR: updateApp: finished calling localSession.saveOrUpdate");
1232                                 // Enable or disable all menu items associated with this app
1233                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1234                                 logger.debug(EELFLoggerDelegate.debugLogger,
1235                                                 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1236                                 transaction.commit();
1237                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1238                                 epUebHelper.addPublisher(app);
1239                                 logger.debug(EELFLoggerDelegate.debugLogger,
1240                                                 "LR: updateApp: finished calling epUebHelper.addPublisher");
1241                                 result = true;
1242                         } catch (Exception e) {
1243                                 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1244                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1245                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1246                                 EcompPortalUtils.rollbackTransaction(transaction,
1247                                                 "updateApp rollback, exception = " + e.toString());
1248                         } finally {
1249                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1250                         }
1251                         if (!result) {
1252                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1253                         }
1254                 }
1255
1256         }
1257
1258         public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1259                         throws GeneralSecurityException, Exception {
1260                 throw new Exception("This method can only be invoked from child class");
1261         }
1262
1263         /**
1264          * Populates a transport model of the application from a database row model.
1265          * Leaves out the thumbnail because the FE fetches images via a different
1266          * API.
1267          * 
1268          * @param app
1269          *            Model of database row
1270          * @param onboardingApp
1271          *            Model for transport as JSON
1272          */
1273         @Override
1274         public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1275                 onboardingApp.id = app.getId();
1276                 onboardingApp.name = app.getName();
1277                 onboardingApp.imageUrl = app.getImageUrl();
1278                 onboardingApp.description = app.getDescription();
1279                 onboardingApp.notes = app.getNotes();
1280                 onboardingApp.url = app.getUrl();
1281                 onboardingApp.alternateUrl = app.getAlternateUrl();
1282                 onboardingApp.restUrl = app.getAppRestEndpoint();
1283                 onboardingApp.isOpen = app.getOpen();
1284                 onboardingApp.isEnabled = app.getEnabled();
1285                 onboardingApp.username = app.getUsername();
1286                 onboardingApp.appPassword = decryptedPassword(app.getAppPassword(), app);
1287                 onboardingApp.uebTopicName = app.getUebTopicName();
1288                 onboardingApp.uebKey = app.getUebKey();
1289                 onboardingApp.uebSecret = app.getUebSecret();
1290                 onboardingApp.isCentralAuth = app.getCentralAuth();
1291                 onboardingApp.nameSpace = app.getNameSpace();
1292                 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1293                 // if (app.getThumbnail() != null)
1294                 // onboardingApp.thumbnail = new
1295                 // String(Base64.getEncoder().encode(app.getThumbnail()));
1296         }
1297
1298         /**
1299          * Creates a database object for an application from an uploaded transport
1300          * model. Must decode the thumbnail, if any.
1301          * 
1302          * @param app
1303          * @param onboardingApp
1304          * @param localSession
1305          * @return The first argument.
1306          */
1307         protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1308                 app.setName(onboardingApp.name);
1309                 app.setDescription(onboardingApp.description);
1310                 app.setNotes(onboardingApp.notes);
1311                 app.setUrl(onboardingApp.url);
1312                 app.setAlternateUrl(onboardingApp.alternateUrl);
1313                 app.setAppRestEndpoint(onboardingApp.restUrl);
1314                 app.setOpen(onboardingApp.isOpen);
1315                 app.setEnabled(onboardingApp.isEnabled);
1316                 app.setUsername(onboardingApp.username);
1317                 app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
1318                 app.setUebTopicName(onboardingApp.uebTopicName);
1319                 app.setUebKey(onboardingApp.uebKey);
1320                 app.setUebSecret(onboardingApp.uebSecret);
1321                 app.setCentralAuth(onboardingApp.isCentralAuth);
1322                 app.setNameSpace(onboardingApp.nameSpace);
1323                 app.setRestrictedApp(onboardingApp.restrictedApp);
1324                 if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
1325                         logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1326                         String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
1327                         logger.debug(EELFLoggerDelegate.debugLogger,
1328                                         "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1329                         if (splitBase64Thumbnail.length > 1) {
1330                                 // This occurs when we have a new image, not an existing image
1331                                 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1332                                 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1333                                 // This is basically a boolean indicator that an image is
1334                                 // present.
1335                                 app.setImageUrl(constructImageName(onboardingApp));
1336                                 app.setThumbnail(decodedImage);
1337                         }
1338                 } else if (app.getThumbnail() != null && onboardingApp.imageLink == null) {
1339                         // The thumbnail that came in from the json is empty; the previous
1340                         // thumbnail is NOT empty. Must delete it.
1341                         logger.debug(EELFLoggerDelegate.debugLogger,
1342                                         "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1343                         app.setImageUrl(null);
1344                         app.setThumbnail(null);
1345                 } else {
1346                         logger.debug(EELFLoggerDelegate.debugLogger,
1347                                         "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1348                 }
1349                 return app;
1350         }
1351
1352         protected String constructImageName(OnboardingApp onboardingApp) {
1353                 return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
1354                                 + ".png";
1355         }
1356
1357         // Don't encrypt or decrypt the password if it is null or the empty string
1358         private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1359                 String result = "";
1360                 if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) {
1361                         try {
1362                                 result = CipherUtil.decryptPKC(encryptedAppPwd,
1363                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1364                         } catch (Exception e) {
1365                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1366                         }
1367                 }
1368                 return result;
1369         }
1370
1371         protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1372                 String result = "";
1373                 if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) {
1374                         try {
1375                                 result = CipherUtil.encryptPKC(decryptedAppPwd,
1376                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1377                         } catch (Exception e) {
1378                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1379                         }
1380                 }
1381                 return result;
1382         }
1383
1384         @SuppressWarnings("unchecked")
1385         @Override
1386         public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1387                 FieldsValidator fieldsValidator = new FieldsValidator();
1388                 final Map<String, Long> params = new HashMap<>();
1389                 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1390
1391                 try {
1392                         params.put("userId", user.getId());
1393                         epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1394                         Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1395                         for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1396                                 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1397                         }
1398                         for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1399                                 if (epWidgetsManPref.getWidgetid() != null) {
1400                                         Long widgetid = epWidgetsManPref.getWidgetid();
1401                                         if (existingWidgetsIds.containsKey(widgetid)) {
1402                                                 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1403                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1404                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1405                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1406                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1407                                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1408                                                 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1409                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1410                                         } else {
1411                                                 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1412                                                 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1413                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1414                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1415                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1416                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1417                                                 epWidgetsManualSort.setUserId(Ints.checkedCast(user.getId()));
1418                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1419                                         }
1420                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1421                                 }
1422                         }
1423                 } catch (Exception e) {
1424                         logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1425                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1426                 }
1427                 return fieldsValidator;
1428         }
1429
1430         @SuppressWarnings("unchecked")
1431         @Override
1432         public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1433                 FieldsValidator fieldsValidator = new FieldsValidator();
1434                 final Map<String, Long> params = new HashMap<>();
1435                 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1436                 try {
1437                         params.put("userId", user.getId());
1438                         epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1439                         Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1440                         for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1441                                 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1442                         }
1443                         for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1444                                 if (delEpWidgetsManPref.getWidgetid() != null) {
1445                                         Long widgetId = delEpWidgetsManPref.getWidgetid();
1446                                         if (existingWidgetIds.containsKey(widgetId)) {
1447                                                 params.put("widgetId",widgetId);
1448                                                 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1449                                         }
1450                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1451                                 }
1452                         }
1453                 } catch (Exception e) {
1454                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1455                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1456                 }
1457                 return fieldsValidator;
1458         }
1459
1460         /*
1461          * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1462          *
1463          * @param: appsSortManual--contains User Apps Data
1464          *
1465          * @param: user--contains LoggedIn User Data
1466          */
1467         @SuppressWarnings("unchecked")
1468         @Override
1469         public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1470                 FieldsValidator fieldsValidator = new FieldsValidator();
1471                 final Map<String, Long> params = new HashMap<>();
1472                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1473
1474                 try {
1475                         params.put("userId", user.getId());
1476                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1477                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1478                         for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1479                                 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1480                         }
1481                         for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1482                                 if (epAppsManPref.getAppid() != null) {
1483                                         Long appid = epAppsManPref.getAppid();
1484                                         if (existingAppIds.containsKey(appid)) {
1485                                                 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1486                                                 epAppsManualSort
1487                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1488                                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1489                                                 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1490                                                 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1491                                         } else {
1492                                                 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1493                                                 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1494                                                 epAppsManualSort
1495                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1496                                                 epAppsManualSort.setUserId(Ints.checkedCast(user.getId()));
1497                                                 dataAccessService.saveDomainObject(epAppsManualSort, null);
1498                                         }
1499                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1500                                 }
1501                         }
1502                 } catch (Exception e) {
1503                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1504                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1505                 }
1506                 return fieldsValidator;
1507         }
1508
1509         /*
1510          * (non-Javadoc)
1511          *
1512          * @see org.openecomp.portalapp.portal.service.EPAppService#
1513          * deleteUserAppSortManual(java.lang.String,
1514          * org.openecomp.portalapp.portal.domain.EPUser)
1515          */
1516         @SuppressWarnings("unchecked")
1517         @Override
1518         public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1519                 FieldsValidator fieldsValidator = new FieldsValidator();
1520                 final Map<String, Long> params = new HashMap<>();
1521                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1522                 try {
1523                         params.put("userId", user.getId());
1524                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1525                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1526                         for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1527                                 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1528                         }
1529                         if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1530                                 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1531                                                 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1532                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1533                         }
1534                 } catch (Exception e) {
1535                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1536                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1537                 }
1538                 return fieldsValidator;
1539         }
1540
1541         @SuppressWarnings("unchecked")
1542         @Override
1543         public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1544                 FieldsValidator fieldsValidator = new FieldsValidator();
1545                 final Map<String, Long> params = new HashMap<>();
1546                 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1547                 EPUserAppsSortPreference usrSortPr = null;
1548                 try {
1549                         params.put("userId", user.getId());
1550                         epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1551                         if (epSortTypes.size() == 0) {
1552                                 usrSortPr = new EPUserAppsSortPreference();
1553                                 usrSortPr.setUserId(Ints.checkedCast(user.getId()));
1554                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1555                                 dataAccessService.saveDomainObject(usrSortPr, null);
1556                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1557                         } else {
1558                                 usrSortPr = epSortTypes.get(0);
1559                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1560                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1561                                 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1562                                 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1563                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1564                         }
1565                 } catch (Exception e) {
1566                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1567                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1568                 }
1569                 return fieldsValidator;
1570         }
1571
1572         @SuppressWarnings("unchecked")
1573         @Override
1574         public String getUserAppsSortTypePreference(EPUser user) {
1575                 final Map<String, Long> params = new HashMap<>();
1576                 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1577                 try {
1578                         params.put("userId", user.getId());
1579                         userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1580                         if (userSortPrefs.size() > 0)
1581                                 return userSortPrefs.get(0).getSortPref();
1582                         else
1583                                 return null;
1584                 } catch (Exception e) {
1585                         logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1586                 }
1587                 return null;
1588
1589         }
1590
1591         @Override
1592         public List<EPApp> getUserRemoteApps(String id) {
1593                 throw new RuntimeException(" Cannot be called from parent class");
1594         }
1595         
1596         @Override
1597         public UserRoles getUserProfileForLeftMenu(String loginId) {
1598                 final Map<String, String> params = new HashMap<>();
1599                 params.put("org_user_id", loginId);
1600                 @SuppressWarnings("unchecked")
1601                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1602                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1603                 if (usersRolesList == null || usersRolesList.size() < 1)
1604                         return null;
1605
1606                 return usersRolesList.get(0);
1607         }
1608         
1609         
1610         @Override
1611         public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1612                 final Map<String, String> params = new HashMap<>();
1613                 params.put("org_user_id", loginId);
1614                 @SuppressWarnings("unchecked")
1615                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1616                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1617                 if (usersRolesList == null || usersRolesList.size() < 1)
1618                         return null;
1619
1620                 return usersRolesList.get(0);
1621         }
1622         
1623         @Override
1624         public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1625                 // Check database.
1626                 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1627                 // If no roles are defined, treat this user as a guest.
1628                 if (user.isGuest() || userAndRoles == null) {
1629                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1630                                         user.getLoginId());
1631                         userAndRoles = createUserRoles(user);
1632                 }
1633
1634                 return userAndRoles;
1635         }
1636         
1637         @Override
1638         public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1639                 // Check database.
1640                 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1641                 // If no roles are defined, treat this user as a guest.
1642                 if (user.isGuest() || userAndRoles == null) {
1643                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1644                                         user.getLoginId());
1645                         userAndRoles = createUserRoles(user);
1646                 }
1647
1648                 return userAndRoles;
1649         }
1650
1651         
1652         public UserRoles createUserRoles(EPUser user)
1653         {
1654                 UserRole userRole = new UserRole();
1655                 userRole.setUser_Id(user.getId());
1656                 userRole.setOrgUserId(user.getLoginId());
1657                 userRole.setFirstName(user.getFirstName());
1658                 userRole.setLastName(user.getLastName());
1659                 userRole.setRoleId(-1L);
1660                 userRole.setRoleName("Guest");
1661                 userRole.setUser_Id(-1L);
1662                 UserRoles userAndRoles = new UserRoles(userRole);
1663                 return userAndRoles;
1664                 
1665         }
1666 }