2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.service;
40 import java.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;
50 import java.util.UUID;
52 import javax.annotation.PostConstruct;
53 import javax.servlet.http.HttpServletResponse;
55 import org.apache.commons.lang.StringUtils;
56 import org.hibernate.Session;
57 import org.hibernate.SessionFactory;
58 import org.hibernate.Transaction;
59 import org.hibernate.criterion.Criterion;
60 import org.hibernate.criterion.Restrictions;
61 import org.onap.portalapp.portal.domain.AdminUserApp;
62 import org.onap.portalapp.portal.domain.AdminUserApplications;
63 import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel;
64 import org.onap.portalapp.portal.domain.AppsResponse;
65 import org.onap.portalapp.portal.domain.EPApp;
66 import org.onap.portalapp.portal.domain.EPUser;
67 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
68 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
69 import org.onap.portalapp.portal.domain.EPUserAppsManualSortPreference;
70 import org.onap.portalapp.portal.domain.EPUserAppsSortPreference;
71 import org.onap.portalapp.portal.domain.EPWidgetsManualSortPreference;
72 import org.onap.portalapp.portal.domain.EcompApp;
73 import org.onap.portalapp.portal.domain.UserRole;
74 import org.onap.portalapp.portal.domain.UserRoles;
75 import org.onap.portalapp.portal.ecomp.model.AppCatalogItem;
76 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
77 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
78 import org.onap.portalapp.portal.transport.EPAppsManualPreference;
79 import org.onap.portalapp.portal.transport.EPAppsSortPreference;
80 import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref;
81 import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
82 import org.onap.portalapp.portal.transport.FieldsValidator;
83 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
84 import org.onap.portalapp.portal.transport.LocalRole;
85 import org.onap.portalapp.portal.transport.OnboardingApp;
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;
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;
104 public class EPAppCommonServiceImpl implements EPAppService {
106 protected String ECOMP_APP_ID = "1";
107 protected String SUPER_ADMIN_ROLE_ID = "1";
108 protected String ACCOUNT_ADMIN_ROLE_ID = "999";
109 protected String RESTRICTED_APP_ROLE_ID = "900";
111 private static final String urlField = "url";
112 private static final String nameField = "name";
114 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
117 private AdminRolesService adminRolesService;
119 protected SessionFactory sessionFactory;
121 private DataAccessService dataAccessService;
124 private void init() {
125 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
126 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
127 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
128 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
132 public List<EPApp> getUserAsAdminApps(EPUser user) {
133 if (adminRolesService.isAccountAdmin(user)) {
134 String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
135 + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
136 + " AND FN_APP.ENABLED = 'Y'";
139 @SuppressWarnings("unchecked")
140 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
142 } catch (Exception e) {
143 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
147 logger.error(EELFLoggerDelegate.errorLogger,
148 "getUserAsAdminApps: only Account Admin may invoke this function!");
149 return new ArrayList<EPApp>();
154 public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
155 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
156 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
157 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
158 + " AND FN_APP.ENABLED = 'Y'";
160 String sql = String.format(format, orgUserId);
164 @SuppressWarnings("unchecked")
165 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
167 } catch (Exception e) {
168 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
174 public List<EPApp> getAppsFullList() {
175 @SuppressWarnings("unchecked")
176 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
181 public List<EcompApp> getEcompAppAppsFullList() {
182 return transformAppsToEcompApps(getAppsFullList());
186 public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
187 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
188 for (EPApp app : appsList) {
189 EcompApp ecompApp = new EcompApp();
190 ecompApp.setId(app.getId());
191 ecompApp.setName(app.getName());
192 ecompApp.setImageUrl(app.getImageUrl());
193 ecompApp.setDescription(app.getDescription());
194 ecompApp.setNotes(app.getNotes());
195 ecompApp.setUrl(app.getUrl());
196 ecompApp.setAlternateUrl(app.getAlternateUrl());
197 ecompApp.setUebTopicName(app.getUebTopicName());
198 ecompApp.setUebKey(app.getUebKey());
199 ecompApp.setUebSecret(app.getUebSecret());
200 ecompApp.setEnabled(app.getEnabled());
201 ecompApp.setCentralAuth(app.getCentralAuth());
202 ecompApp.setNameSpace(app.getNameSpace());
203 ecompApp.setRestrictedApp(app.isRestrictedApp());
204 ecompAppList.add(ecompApp);
210 public EPApp getApp(Long appId) {
212 return (EPApp) dataAccessService.getDomainObject(EPApp.class, appId, null);
213 } catch (Exception e) {
214 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
219 @SuppressWarnings("unchecked")
221 public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
222 if (adminRolesService.isAccountAdmin(user)) {
223 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 "
224 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
225 + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
226 String sql = String.format(format, user.getId());
227 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
228 // app.APP_REST_ENDPOINT <> ''";
231 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
232 } catch (Exception e) {
233 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
234 logger.error(EELFLoggerDelegate.errorLogger,
235 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
238 return new ArrayList<AppIdAndNameTransportModel>();
242 public EPApp getAppDetail(String appName) {
243 final Map<String, String> params = new HashMap<String, String>();
245 params.put("appName", appName);
246 @SuppressWarnings("unchecked")
247 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
248 return (apps.size() > 0) ? apps.get(0) : null;
249 } catch(Exception e) {
250 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
256 public EPApp getAppDetailByAppName(String appName) {
257 final Map<String, String> params = new HashMap<String, String>();
259 params.put("appName", appName);
260 @SuppressWarnings("unchecked")
261 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getAppDetailsByAppName", params, null);
262 if (apps.size() > 0) {
263 EPApp app = apps.get(0);
264 if (!EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
265 app.setCentralAuth(false);
271 } catch (Exception e) {
272 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
277 @SuppressWarnings("unchecked")
279 public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
280 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
283 if (adminRolesService.isSuperAdmin(user)) {
284 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
285 + "where app.ENABLED = 'Y' AND app.app_type = 1";
287 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 "
288 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
289 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
291 sql = String.format(format, user.getId());
292 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
293 // app.APP_REST_ENDPOINT <> ''";
296 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
297 } catch (Exception e) {
298 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
299 logger.error(EELFLoggerDelegate.errorLogger,
300 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
303 return new ArrayList<AppIdAndNameTransportModel>();
306 protected void logQuery(String sql) {
307 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
310 public DataAccessService getDataAccessService() {
311 return dataAccessService;
314 public void setDataAccessService(DataAccessService dataAccessService) {
315 this.dataAccessService = dataAccessService;
318 @SuppressWarnings("unchecked")
320 public List<AdminUserApplications> getAppsAdmins() {
322 Map<String, String> params = new HashMap<>();
323 params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
324 List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
326 return aggregateRowsResultsByUserId(adminApps);
327 } catch (Exception e) {
328 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
333 private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
334 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
335 for (AdminUserApp app : adminApps) {
336 Long userId = app.getUser_Id();
337 if (adminUserApplications.get(userId) == null)
338 adminUserApplications.put(userId, new AdminUserApplications(app));
340 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
342 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
346 public List<AppsResponse> getAllApps(Boolean all) {
347 // If all is true, return both active and inactive apps. Otherwise, just
349 @SuppressWarnings("unchecked")
350 // Sort the list by application name so the drop-down looks pretty.
351 List<EPApp> apps = all
352 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
353 : (List<EPApp>) dataAccessService.getList(EPApp.class,
354 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
356 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
357 for (EPApp app : apps) {
358 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
364 public UserRoles getUserProfile(String loginId) {
365 final Map<String, String> params = new HashMap<>();
366 params.put("org_user_id", loginId);
367 @SuppressWarnings("unchecked")
368 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
369 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
370 if (usersRolesList == null || usersRolesList.size() < 1)
373 return usersRolesList.get(0);
377 public UserRoles getUserProfileNormalized(EPUser user) {
379 UserRoles userAndRoles = getUserProfile(user.getLoginId());
380 // If no roles are defined, treat this user as a guest.
381 if (user.isGuest() || userAndRoles == null) {
382 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
384 UserRole userRole = new UserRole();
385 userRole.setUser_Id(user.getId());
386 userRole.setOrgUserId(user.getLoginId());
387 userRole.setFirstName(user.getFirstName());
388 userRole.setLastName(user.getLastName());
389 userRole.setRoleId(-1L);
390 userRole.setRoleName("Guest");
391 userRole.setUser_Id(-1L);
392 userAndRoles = new UserRoles(userRole);
398 protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
399 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
400 for (UserRole user : userRoleList) {
401 String orgUserId = user.getOrgUserId();
402 if (userRoles.get(orgUserId) == null)
403 userRoles.put(orgUserId, new UserRoles(user));
405 userRoles.get(orgUserId).addRole(user.getRoleName());
407 return new ArrayList<UserRoles>(userRoles.values());
410 private boolean isRestrictedApp(Long appId) {
411 EPApp app = getApp(appId);
412 return app.isRestrictedApp();
415 // For the functional menu edit
417 public List<LocalRole> getAppRoles(Long appId) {
419 if (isRestrictedApp(appId)) {
420 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
421 }else if(appId == 1){
422 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
424 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
427 @SuppressWarnings("unchecked")
428 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
432 protected String userAppsQuery(EPUser user) {
433 StringBuilder query = new StringBuilder();
434 if (adminRolesService.isSuperAdmin(user)) {
435 query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
437 query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
439 "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
440 query.append(" AND FN_APP.ENABLED = 'Y'");
442 return query.toString();
445 protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
446 FieldsValidator fieldsValidator = new FieldsValidator();
447 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
448 || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
449 || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
450 || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID))
451 // For a normal app (appType==1), these fields must be filled
453 // For a restricted app (appType==2), they will be empty.
454 || ((!onboardingApp.restrictedApp)
455 && (onboardingApp.username == null || onboardingApp.username.length() == 0
456 || onboardingApp.appPassword == null || onboardingApp.appPassword.length() == 0))) {
457 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
459 return fieldsValidator;
463 public List<EPApp> getUserApps(EPUser user) {
464 List<EPApp> openApps = getOpenApps();
466 if (user.isGuest()) {
469 String sql = userAppsQuery(user);
472 // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
473 List<EPApp> appsList = new ArrayList<>();
474 @SuppressWarnings("unchecked")
475 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
476 HashSet<EPApp> appSet = new HashSet<>();
477 for (EPApp app : adminApps) {
482 for (EPApp app : openApps) {
483 if (!appSet.contains(app))
492 public List<EPApp> getPersAdminApps(EPUser user) {
493 final Map<String, Long> params = new HashMap<>();
494 params.put("userId", user.getId());
495 // Named query is stored in EP.hbm.xml, mapped to EPApp
496 @SuppressWarnings("unchecked")
497 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
502 public List<EPApp> getPersUserApps(EPUser user) {
503 final Map<String, Long> params = new HashMap<>();
504 params.put("userId", user.getId());
505 // Named query is stored in EP.hbm.xml, mapped to EPApp
506 @SuppressWarnings("unchecked")
507 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
515 * org.onap.portalapp.portal.service.EPAppService#getAppCatalog(
516 * org.onap.portalapp.portal.domain.EPUser)
519 public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
520 final Map<String, Long> params = new HashMap<>();
521 params.put("userId", user.getId());
522 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
523 @SuppressWarnings("unchecked")
524 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
532 * org.onap.portalapp.portal.service.EPAppService#getAdminAppCatalog(
533 * org.onap.portalapp.portal.domain.EPUser)
536 public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
537 final Map<String, Long> params = new HashMap<>();
538 params.put("userId", user.getId());
539 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
540 @SuppressWarnings("unchecked")
541 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
545 private List<EPApp> getOpenApps() {
546 @SuppressWarnings("unchecked")
547 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
551 @SuppressWarnings("unchecked")
553 public List<EPApp> getAppsOrderByName(EPUser user) {
554 final Map<String, Long> params = new HashMap<>();
555 List<EPApp> sortedAppsByName = null;
557 if (adminRolesService.isSuperAdmin(user)) {
558 params.put("userId", user.getId());
559 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
561 params.put("userId", user.getId());
562 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
564 } catch (Exception e) {
565 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
567 return sortedAppsByName;
570 @SuppressWarnings("unchecked")
572 public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
574 final Map<String, Long> params = new HashMap<>();
575 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
576 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
578 if (adminRolesService.isSuperAdmin(user)) {
579 params.put("userId", user.getId());
580 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
582 params.put("userId", user.getId());
583 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
585 Set<String> epAppSet = new HashSet<String>();
586 for (EPApp eapp : sortedAppsByLastUsed)
587 if (!epAppSet.contains(eapp.getName())) {
588 finalsortedAppsByLastUsed.add(eapp);
589 epAppSet.add(eapp.getName());
592 } catch (Exception e) {
593 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
595 return finalsortedAppsByLastUsed;
598 @SuppressWarnings("unchecked")
600 public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
601 final Map<String, Long> params = new HashMap<>();
602 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
603 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
605 if (adminRolesService.isSuperAdmin(user)) {
606 params.put("userId", user.getId());
607 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
609 params.put("userId", user.getId());
610 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
612 Set<String> epAppSet = new HashSet<String>();
614 for (EPApp eapp : sortedAppsByMostUsed) {
615 if (!epAppSet.contains(eapp.getName())) {
616 finalsortedAppsByMostUsed.add(eapp);
617 epAppSet.add(eapp.getName());
620 } catch (Exception e) {
621 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
624 return finalsortedAppsByMostUsed;
628 * This Method retrieves the User Apps by Sort Manual Preference
630 * @param: user--contains LoggedIn User Data
632 @SuppressWarnings("unchecked")
634 public List<EPApp> getAppsOrderByManual(EPUser user) {
635 final Map<String, Long> params = new HashMap<>();
636 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
637 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
639 if (adminRolesService.isSuperAdmin(user)) {
640 params.put("userId", user.getId());
641 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
643 params.put("userId", user.getId());
644 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
646 Set<String> epAppSet = new HashSet<String>();
648 for (EPApp eapp : sortedAppsByManual) {
649 if (!epAppSet.contains(eapp.getName())) {
650 finalsortedAppsByManual.add(eapp);
651 epAppSet.add(eapp.getName());
654 } catch (Exception e) {
655 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
657 return finalsortedAppsByManual;
661 public List<OnboardingApp> getOnboardingApps() {
662 @SuppressWarnings("unchecked")
663 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
664 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
665 for (EPApp app : apps) {
666 OnboardingApp onboardingApp = new OnboardingApp();
667 app.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);//to hide password from get request
668 createOnboardingFromApp(app, onboardingApp);
669 onboardingAppsList.add(onboardingApp);
671 return onboardingAppsList;
675 public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
676 @SuppressWarnings("unchecked")
677 List<EPApp> apps = dataAccessService.getList(EPApp.class,
678 " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
679 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
680 for (EPApp app : apps) {
681 OnboardingApp onboardingApp = new OnboardingApp();
682 app.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request
683 createOnboardingFromApp(app, onboardingApp);
684 onboardingAppsList.add(onboardingApp);
686 return onboardingAppsList;
689 @SuppressWarnings("unchecked")
690 private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
691 boolean duplicatedUrl = false;
692 boolean duplicatedName = false;
694 if (onboardingApp.id == null) {
695 List<Criterion> restrictionsList = new ArrayList<Criterion>();
696 Criterion urlCrit =Restrictions.eq("url", onboardingApp.url);
697 Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);
698 Criterion orCrit = Restrictions.or(urlCrit, nameCrit);
700 restrictionsList.add(orCrit);
701 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
705 List<Criterion> restrictionsList = new ArrayList<Criterion>();
706 Criterion idCrit =Restrictions.eq("id", onboardingApp.id);
707 Criterion urlCrit =Restrictions.eq("url", onboardingApp.url);
708 Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);
709 Criterion orCrit = Restrictions.or(idCrit, urlCrit, nameCrit);
711 restrictionsList.add(orCrit);
712 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
715 for (EPApp app : apps) {
716 if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) {
719 if (!duplicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) {
720 duplicatedUrl = true;
721 if (duplicatedName) {
725 if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
726 duplicatedName = true;
732 if (duplicatedUrl || duplicatedName) {
734 fieldsValidator.addProblematicFieldName(urlField);
736 if (duplicatedName) {
737 fieldsValidator.addProblematicFieldName(nameField);
739 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
740 fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
745 public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
746 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
747 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
748 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
749 validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
751 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
752 if (modifiedOnboardingApp.id != null) {
753 updateApp(modifiedOnboardingApp.id, modifiedOnboardingApp, fieldsValidator, user);
755 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
758 return fieldsValidator;
762 public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
763 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
764 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
765 validateOnboardingApp(newOnboardingApp, fieldsValidator);
767 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
768 if (newOnboardingApp.id == null) {
769 updateApp(null, newOnboardingApp, fieldsValidator, user);
771 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
774 return fieldsValidator;
777 @SuppressWarnings("unchecked")
779 public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
780 FieldsValidator fieldsValidator = new FieldsValidator();
781 if (!adminRolesService.isSuperAdmin(user)) {
782 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
783 return fieldsValidator;
785 final Map<String, Long> params = new HashMap<>();
786 params.put("app_id", appid);
787 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
788 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
789 for(int i=0;i<EPUserAppRolesRequestList.size();i++)
791 dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
794 Session localSession = null;
795 Transaction transaction = null;
796 Boolean result = false;
798 localSession = sessionFactory.openSession();
799 transaction = localSession.beginTransaction();
801 // 1) Remove the URL for any functional menu item associated with
803 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
804 // Named query is stored in EP.hbm.xml, mapped to EPApp
805 dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
806 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted URL for any functional menu item associated with app");
808 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
809 // 2)Remove any favorites associated with a menu item that is
810 // associated with this app
811 dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
812 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
814 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
815 // 3)Remove all role, appid records from fn_menu_functional_role
816 // that are associated with this app
817 dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
818 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
820 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
821 // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
822 // that are associated with this app
823 dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
824 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
826 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
827 // 5)Remove all rolefunctions, appid records from ep_app_function
828 // that are associated with this app
829 dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
830 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
832 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
833 // 6)Remove all records from fn_user_role associated with this app
834 dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
835 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
837 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
838 // 7)Remove any widgets associated with this app
839 dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
840 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
842 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
843 // 8)Remove any roles associated with this app
844 dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
845 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
847 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
848 // 9)Remove all records from fn_role associated with this app
849 dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
850 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
852 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
853 // 10)Remove app contact us entries
854 dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
855 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
857 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
858 // 11)Remove rows in the app personalization selection table
859 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
860 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
862 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
863 // 12)Remove rows in the app personalization sort table
864 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
865 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
867 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
868 // 13)Remove rows in the app personalization sort table
869 dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
870 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
872 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
873 // 14)Remove rows in the ep_web_analytics_source
874 dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
875 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
877 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
879 dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
880 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
883 // 1) Remove the URL for any functional menu item associated with
885 String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
886 + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
888 Query query = localSession.createSQLQuery(sql);
889 query.executeUpdate();
891 // Remove any favorites associated with a menu item that is
892 // associated with this app
893 sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
894 + " where fn_menu_functional_roles.app_id='" + appid + "' "
895 + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
897 query = localSession.createSQLQuery(sql);
898 query.executeUpdate();
900 // Remove all role, appid records from fn_menu_functional_role
901 // that are associated with this app
902 sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
904 query = localSession.createSQLQuery(sql);
905 query.executeUpdate();
908 // Remove all roles, rolefunctions, appid records from ep_app_role_function
909 // that are associated with this app
910 sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
911 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
912 query = localSession.createSQLQuery(sql);
913 query.executeUpdate();
915 //Remove all rolefunctions, appid records from ep_app_function
916 // that are associated with this app
917 sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
918 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
919 query = localSession.createSQLQuery(sql);
920 query.executeUpdate();
922 // Remove all records from fn_user_role associated with this app
923 sql = "delete from fn_user_role where app_id='" + appid + "'";
925 query = localSession.createSQLQuery(sql);
926 query.executeUpdate();
928 // Remove any widgets associated with this app
929 sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
931 query = localSession.createSQLQuery(sql);
932 query.executeUpdate();
934 // Remove any roles associated with this app
935 sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
936 + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
938 query = localSession.createSQLQuery(sql);
939 query.executeUpdate();
941 // Remove all records from fn_role associated with this app
942 sql = "delete from fn_role where app_id='" + appid + "'";
944 query = localSession.createSQLQuery(sql);
945 query.executeUpdate();
947 // Remove app contact us entries
948 sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
950 query = localSession.createSQLQuery(sql);
951 query.executeUpdate();
953 // Remove rows in the app personalization selection table
954 sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
956 query = localSession.createSQLQuery(sql);
957 query.executeUpdate();
959 // Remove rows in the app personalization sort table
960 sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
962 query = localSession.createSQLQuery(sql);
963 query.executeUpdate();
965 // Remove rows in the app personalization sort table
966 sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
968 query = localSession.createSQLQuery(sql);
969 query.executeUpdate();
971 // Remove rows in the app personalization sort table
972 sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
974 query = localSession.createSQLQuery(sql);
975 query.executeUpdate();
978 sql = "delete from fn_app where app_id='" + appid + "'";
980 query = localSession.createSQLQuery(sql);
981 query.executeUpdate();
983 transaction.commit();
986 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
987 } catch (Exception e) {
988 logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
989 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
990 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
992 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
995 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
997 return fieldsValidator;
1000 private static Object syncRests = new Object();
1002 // An app has been enabled/disabled. Must enable/disable all associated
1003 // functional menu items.
1004 protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1005 String active_yn = enabled ? "Y" : "N";
1006 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1007 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1008 + " AND r.app_id = '" + appId + "' ";
1010 @SuppressWarnings("unchecked")
1011 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1012 for (FunctionalMenuItem menuItem : menuItems) {
1013 FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1015 myMenuItem.active_yn = active_yn;
1016 localSession.save(myMenuItem);
1020 // Attention! If (appId == null) we use this function to create application
1021 // otherwise we use it to modify existing application
1022 protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1023 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1024 // Separate out the code for a restricted app, since it doesn't need any
1026 if (onboardingApp.restrictedApp) {
1027 boolean result = false;
1028 Session localSession = null;
1029 Transaction transaction = null;
1031 localSession = sessionFactory.openSession();
1032 transaction = localSession.beginTransaction();
1034 if (appId == null) {
1037 app = (EPApp) localSession.get(EPApp.class, appId);
1038 if (app == null || app.getId() == null) { // App is already
1040 transaction.commit();
1041 localSession.close();
1042 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1046 createAppFromOnboarding(app, onboardingApp, localSession);
1047 localSession.saveOrUpdate(app);
1048 // Enable or disable all menu items associated with this app
1049 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1050 transaction.commit();
1052 } catch (Exception e) {
1053 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1054 EcompPortalUtils.rollbackTransaction(transaction,
1055 "updateApp rollback, exception = " + e.toString());
1057 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1060 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1064 updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1070 protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1072 synchronized (syncRests) {
1073 boolean result = false;
1074 Session localSession = null;
1075 Transaction transaction = null;
1077 localSession = sessionFactory.openSession();
1078 transaction = localSession.beginTransaction();
1080 if (appId == null) {
1083 * In the parent class, the UEB code is responsible for generating the
1084 * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1085 * may be used in future at which point we can just remove this method and
1086 * depend on parent class's method So, using UUID generator to generate the
1087 * unique key instead.
1089 String uuidStr = UUID.randomUUID().toString();
1090 String appKey = uuidStr;
1091 String appSecret = uuidStr;
1092 String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1093 onboardingApp.setUebTopicName(appMailboxName);
1094 onboardingApp.setUebKey(appKey);
1095 onboardingApp.setUebSecret(appSecret);
1097 app = (EPApp) localSession.get(EPApp.class, appId);
1098 if (app == null || app.getId() == null) {
1099 // App is already deleted!
1100 transaction.commit();
1101 localSession.close();
1102 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1106 logger.debug(EELFLoggerDelegate.debugLogger,
1107 "updateRestrictedApp: about to call createAppFromOnboarding");
1108 createAppFromOnboarding(app, onboardingApp, localSession);
1109 logger.debug(EELFLoggerDelegate.debugLogger,
1110 "updateRestrictedApp: finished calling createAppFromOnboarding");
1111 localSession.saveOrUpdate(app);
1112 logger.debug(EELFLoggerDelegate.debugLogger,
1113 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1114 // Enable or disable all menu items associated with this app
1115 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1116 logger.debug(EELFLoggerDelegate.debugLogger,
1117 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1118 transaction.commit();
1119 logger.debug(EELFLoggerDelegate.debugLogger,
1120 "updateRestrictedApp: finished calling transaction.commit");
1122 } catch (Exception e) {
1123 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1124 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1125 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1126 EcompPortalUtils.rollbackTransaction(transaction,
1127 "updateRestrictedApp rollback, exception = " + e.toString());
1129 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1132 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1139 protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1141 synchronized (syncRests) {
1142 boolean result = false;
1143 Session localSession = null;
1144 Transaction transaction = null;
1146 localSession = sessionFactory.openSession();
1147 transaction = localSession.beginTransaction();
1149 if (appId == null) {
1151 // -------------------------------------------------------------------------------------------
1152 // Register this App with the UEB communication server.
1154 // the App's unique mailbox/topic
1155 // name and keys to the FN_APP table. The App's mailbox
1157 // keys will be visible to the
1158 // admin on the ONAP portal.
1159 // -------------------------------------------------------------------------------------------
1160 TopicManager topicManager = new TopicManager() {
1162 EPAppCommonServiceImpl service;
1164 public void init(EPAppCommonServiceImpl _service) {
1168 public void createTopic(String key, String secret, String topicName,
1169 String topicDescription) throws HttpException, CambriaApiException, IOException {
1171 init(EPAppCommonServiceImpl.this);
1172 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1173 if (logger.isInfoEnabled()) {
1174 logger.info("==> createTopic");
1175 logger.info("topicName: " + topicName);
1176 logger.info("topicDescription: " + topicDescription);
1178 CambriaTopicManager tm = null;
1180 tm = service.getTopicManager(urlList, key, secret);
1181 } catch (Exception e) {
1182 logger.error("pub.build Exception ", e);
1183 throw new CambriaApiException(topicName);
1185 tm.createTopic(topicName, topicDescription, 1, 1);
1188 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1189 String topicName) throws HttpException, CambriaApiException, IOException {
1190 logger.info("==> addPublisher to topic " + topicName);
1191 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1192 CambriaTopicManager tm = null;
1194 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1195 } catch (Exception e) {
1196 logger.error("pub.build Exception ", e);
1197 throw new CambriaApiException(topicName);
1199 tm.allowProducer(topicName, publisherKey);
1203 final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1204 .usingHosts(Helper.uebUrlList()).build();
1205 com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1206 "ONAP Portal Owner");
1207 String appKey = credential.getApiKey();
1208 String appSecret = credential.getApiSecret();
1209 String appMailboxName = null;
1211 int maxNumAttemptsToCreateATopic = 3;
1212 boolean successfullyCreatedMailbox = false;
1213 for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1214 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1217 topicManager.createTopic(
1218 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1219 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1220 appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
1221 successfullyCreatedMailbox = true;
1222 logger.debug(EELFLoggerDelegate.debugLogger,
1223 "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
1224 logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
1225 + appSecret + " generated using = " + user.getEmail());
1227 } catch (HttpException e) {
1228 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1229 if (e.getStatusCode() == 409) {
1230 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1231 + " already exists. Will try using a different name", e);
1233 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1239 if (successfullyCreatedMailbox) {
1240 onboardingApp.setUebTopicName(appMailboxName);
1241 onboardingApp.setUebKey(appKey);
1242 onboardingApp.setUebSecret(appSecret);
1246 * EP is a publisher to this App's new mailbox
1248 topicManager.addPublisher(
1249 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1250 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1251 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1255 * This App is a subscriber of its own mailbox
1257 topicManager.addSubscriber(
1258 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1259 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1263 * This App is a publisher to EP
1265 topicManager.addPublisher(
1266 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1267 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1268 PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1269 } catch (HttpException | CambriaApiException | IOException e) {
1270 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1271 logger.error(EELFLoggerDelegate.errorLogger,
1272 "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1273 transaction.commit();
1274 localSession.close();
1275 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1279 transaction.commit();
1280 localSession.close();
1281 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1285 app = (EPApp) localSession.get(EPApp.class, appId);
1286 if (app == null || app.getId() == null) {
1287 // App is already deleted!
1288 transaction.commit();
1289 localSession.close();
1290 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1294 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1295 createAppFromOnboarding(app, onboardingApp, localSession);
1296 logger.debug(EELFLoggerDelegate.debugLogger,
1297 "LR: updateApp: finished calling createAppFromOnboarding");
1298 localSession.saveOrUpdate(app);
1299 logger.debug(EELFLoggerDelegate.debugLogger,
1300 "LR: updateApp: finished calling localSession.saveOrUpdate");
1301 // Enable or disable all menu items associated with this app
1302 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1303 logger.debug(EELFLoggerDelegate.debugLogger,
1304 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1305 transaction.commit();
1306 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1307 logger.debug(EELFLoggerDelegate.debugLogger,
1308 "LR: updateApp: finished calling epUebHelper.addPublisher");
1310 } catch (Exception e) {
1311 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1312 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1313 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1314 EcompPortalUtils.rollbackTransaction(transaction,
1315 "updateApp rollback, exception = " + e.toString());
1317 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1320 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1326 public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1327 throws GeneralSecurityException, Exception {
1328 throw new Exception("This method can only be invoked from child class");
1332 * Populates a transport model of the application from a database row model.
1333 * Leaves out the thumbnail because the FE fetches images via a different
1337 * Model of database row
1338 * @param onboardingApp
1339 * Model for transport as JSON
1342 public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1343 onboardingApp.id = app.getId();
1344 onboardingApp.name = app.getName();
1345 onboardingApp.imageUrl = app.getImageUrl();
1346 onboardingApp.description = app.getDescription();
1347 onboardingApp.notes = app.getNotes();
1348 onboardingApp.url = app.getUrl();
1349 onboardingApp.alternateUrl = app.getAlternateUrl();
1350 onboardingApp.restUrl = app.getAppRestEndpoint();
1351 onboardingApp.isOpen = app.getOpen();
1352 onboardingApp.isEnabled = app.getEnabled();
1353 onboardingApp.username = app.getUsername();
1354 onboardingApp.appPassword = (app.getAppPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) ? EPCommonSystemProperties.APP_DISPLAY_PASSWORD :decryptedPassword(app.getAppPassword(), app);
1355 onboardingApp.uebTopicName = app.getUebTopicName();
1356 onboardingApp.uebKey = app.getUebKey();
1357 onboardingApp.uebSecret = app.getUebSecret();
1358 onboardingApp.isCentralAuth = app.getCentralAuth();
1359 onboardingApp.nameSpace = app.getNameSpace();
1360 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1361 // if (app.getThumbnail() != null)
1362 // onboardingApp.thumbnail = new
1363 // String(Base64.getEncoder().encode(app.getThumbnail()));
1367 * Creates a database object for an application from an uploaded transport
1368 * model. Must decode the thumbnail, if any.
1371 * @param onboardingApp
1372 * @param localSession
1373 * @return The first argument.
1375 protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1376 app.setName(onboardingApp.name);
1377 app.setDescription(onboardingApp.description);
1378 app.setNotes(onboardingApp.notes);
1379 app.setUrl(onboardingApp.url);
1380 app.setAlternateUrl(onboardingApp.alternateUrl);
1381 app.setAppRestEndpoint(onboardingApp.restUrl);
1382 app.setOpen(onboardingApp.isOpen);
1383 app.setEnabled(onboardingApp.isEnabled);
1384 app.setUsername(onboardingApp.username);
1385 if(!onboardingApp.appPassword.equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1386 app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
1387 //app.setUebTopicName(onboardingApp.uebTopicName);
1388 app.setUebKey(onboardingApp.uebKey);
1389 app.setUebSecret(onboardingApp.uebSecret);
1390 app.setCentralAuth(onboardingApp.isCentralAuth);
1391 app.setNameSpace(onboardingApp.nameSpace);
1392 app.setRestrictedApp(onboardingApp.restrictedApp);
1393 if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
1394 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1395 String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
1396 logger.debug(EELFLoggerDelegate.debugLogger,
1397 "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1398 if (splitBase64Thumbnail.length > 1) {
1399 // This occurs when we have a new image, not an existing image
1400 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1401 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1402 // This is basically a boolean indicator that an image is
1404 app.setImageUrl(constructImageName(onboardingApp));
1405 app.setThumbnail(decodedImage);
1407 } else if (app.getThumbnail() != null && onboardingApp.imageLink == null) {
1408 // The thumbnail that came in from the json is empty; the previous
1409 // thumbnail is NOT empty. Must delete it.
1410 logger.debug(EELFLoggerDelegate.debugLogger,
1411 "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1412 app.setImageUrl(null);
1413 app.setThumbnail(null);
1415 logger.debug(EELFLoggerDelegate.debugLogger,
1416 "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1421 protected String constructImageName(OnboardingApp onboardingApp) {
1422 return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
1426 // Don't encrypt or decrypt the password if it is null or the empty string
1427 private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1429 if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) {
1431 result = CipherUtil.decryptPKC(encryptedAppPwd,
1432 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1433 } catch (Exception e) {
1434 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1440 protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1442 if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) {
1444 result = CipherUtil.encryptPKC(decryptedAppPwd,
1445 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1446 } catch (Exception e) {
1447 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1453 @SuppressWarnings("unchecked")
1455 public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1456 FieldsValidator fieldsValidator = new FieldsValidator();
1457 final Map<String, Long> params = new HashMap<>();
1458 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1461 params.put("userId", user.getId());
1462 epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1463 Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1464 for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1465 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1467 for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1468 if (epWidgetsManPref.getWidgetid() != null) {
1469 Long widgetid = epWidgetsManPref.getWidgetid();
1470 if (existingWidgetsIds.containsKey(widgetid)) {
1471 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1472 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1473 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1474 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1475 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1476 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1477 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1478 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1480 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1481 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1482 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1483 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1484 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1485 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1486 epWidgetsManualSort.setUserId(user.getId());
1487 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1489 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1492 } catch (Exception e) {
1493 logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1494 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1496 return fieldsValidator;
1499 @SuppressWarnings("unchecked")
1501 public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1502 FieldsValidator fieldsValidator = new FieldsValidator();
1503 final Map<String, Long> params = new HashMap<>();
1504 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1506 params.put("userId", user.getId());
1507 epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1508 Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1509 for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1510 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1512 for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1513 if (delEpWidgetsManPref.getWidgetid() != null) {
1514 Long widgetId = delEpWidgetsManPref.getWidgetid();
1515 if (existingWidgetIds.containsKey(widgetId)) {
1516 params.put("widgetId",widgetId);
1517 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1519 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1522 } catch (Exception e) {
1523 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1524 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1526 return fieldsValidator;
1530 * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1532 * @param: appsSortManual--contains User Apps Data
1534 * @param: user--contains LoggedIn User Data
1536 @SuppressWarnings("unchecked")
1538 public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1539 FieldsValidator fieldsValidator = new FieldsValidator();
1540 final Map<String, Long> params = new HashMap<>();
1541 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1544 params.put("userId", user.getId());
1545 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1546 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1547 for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1548 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1550 for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1551 if (epAppsManPref.getAppid() != null) {
1552 Long appid = epAppsManPref.getAppid();
1553 if (existingAppIds.containsKey(appid)) {
1554 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1556 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1557 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1558 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1559 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1561 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1562 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1564 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1565 epAppsManualSort.setUserId(user.getId());
1566 dataAccessService.saveDomainObject(epAppsManualSort, null);
1568 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1571 } catch (Exception e) {
1572 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1573 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1575 return fieldsValidator;
1581 * @see org.onap.portalapp.portal.service.EPAppService#
1582 * deleteUserAppSortManual(java.lang.String,
1583 * org.onap.portalapp.portal.domain.EPUser)
1585 @SuppressWarnings("unchecked")
1587 public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1588 FieldsValidator fieldsValidator = new FieldsValidator();
1589 final Map<String, Long> params = new HashMap<>();
1590 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1592 params.put("userId", user.getId());
1593 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1594 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1595 for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1596 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1598 if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1599 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1600 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1601 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1603 } catch (Exception e) {
1604 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1605 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1607 return fieldsValidator;
1610 @SuppressWarnings("unchecked")
1612 public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1613 FieldsValidator fieldsValidator = new FieldsValidator();
1614 final Map<String, Long> params = new HashMap<>();
1615 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1616 EPUserAppsSortPreference usrSortPr = null;
1618 params.put("userId", user.getId());
1619 epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1620 if (epSortTypes.size() == 0) {
1621 usrSortPr = new EPUserAppsSortPreference();
1622 usrSortPr.setUserId((int)(long)(user.getId()));
1623 usrSortPr.setSortPref(appsSortPreference.getValue());
1624 dataAccessService.saveDomainObject(usrSortPr, null);
1625 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1627 usrSortPr = epSortTypes.get(0);
1628 usrSortPr.setSortPref(appsSortPreference.getValue());
1629 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1630 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1631 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1632 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1634 } catch (Exception e) {
1635 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1636 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1638 return fieldsValidator;
1641 @SuppressWarnings("unchecked")
1643 public String getUserAppsSortTypePreference(EPUser user) {
1644 final Map<String, Long> params = new HashMap<>();
1645 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1647 params.put("userId", user.getId());
1648 userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1649 if (userSortPrefs.size() > 0)
1650 return userSortPrefs.get(0).getSortPref();
1653 } catch (Exception e) {
1654 logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1661 public List<EPApp> getUserRemoteApps(String id) {
1662 throw new RuntimeException(" Cannot be called from parent class");
1666 public UserRoles getUserProfileForLeftMenu(String loginId) {
1667 final Map<String, String> params = new HashMap<>();
1668 params.put("org_user_id", loginId);
1669 @SuppressWarnings("unchecked")
1670 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1671 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1672 if (usersRolesList == null || usersRolesList.size() < 1)
1675 return usersRolesList.get(0);
1680 public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1681 final Map<String, String> params = new HashMap<>();
1682 params.put("org_user_id", loginId);
1683 @SuppressWarnings("unchecked")
1684 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1685 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1686 if (usersRolesList == null || usersRolesList.size() < 1)
1689 return usersRolesList.get(0);
1693 public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1695 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1696 // If no roles are defined, treat this user as a guest.
1697 if (user.isGuest() || userAndRoles == null) {
1698 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1700 userAndRoles = createUserRoles(user);
1703 return userAndRoles;
1707 public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1709 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1710 // If no roles are defined, treat this user as a guest.
1711 if (user.isGuest() || userAndRoles == null) {
1712 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1714 userAndRoles = createUserRoles(user);
1717 return userAndRoles;
1721 public UserRoles createUserRoles(EPUser user)
1723 UserRole userRole = new UserRole();
1724 userRole.setUser_Id(user.getId());
1725 userRole.setOrgUserId(user.getLoginId());
1726 userRole.setFirstName(user.getFirstName());
1727 userRole.setLastName(user.getLastName());
1728 userRole.setRoleId(-1L);
1729 userRole.setRoleName("Guest");
1730 userRole.setUser_Id(-1L);
1731 UserRoles userAndRoles = new UserRoles(userRole);
1732 return userAndRoles;