2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
10 * Unless otherwise specified, all software contained herein is licensed
11 * under the Apache License, Version 2.0 (the "License");
12 * you may not use this software except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * Unless otherwise specified, all documentation contained herein is licensed
24 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 * you may not use this documentation except in compliance with the License.
26 * You may obtain a copy of the License at
28 * https://creativecommons.org/licenses/by/4.0/
30 * Unless required by applicable law or agreed to in writing, documentation
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
36 * ============LICENSE_END============================================
40 package org.onap.portalapp.portal.service;
42 import java.io.IOException;
43 import java.security.GeneralSecurityException;
44 import java.util.ArrayList;
45 import java.util.Base64;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.LinkedList;
49 import java.util.List;
52 import java.util.UUID;
53 import java.util.stream.Collectors;
55 import javax.annotation.PostConstruct;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.lang.StringUtils;
59 import org.hibernate.Session;
60 import org.hibernate.SessionFactory;
61 import org.hibernate.Transaction;
62 import org.hibernate.criterion.Criterion;
63 import org.hibernate.criterion.Restrictions;
64 import org.json.JSONArray;
65 import org.json.JSONObject;
66 import org.onap.portalapp.portal.domain.AdminUserApp;
67 import org.onap.portalapp.portal.domain.AdminUserApplications;
68 import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel;
69 import org.onap.portalapp.portal.domain.AppsResponse;
70 import org.onap.portalapp.portal.domain.EPApp;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
73 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
74 import org.onap.portalapp.portal.domain.EPUserAppsManualSortPreference;
75 import org.onap.portalapp.portal.domain.EPUserAppsSortPreference;
76 import org.onap.portalapp.portal.domain.EPWidgetsManualSortPreference;
77 import org.onap.portalapp.portal.domain.EcompApp;
78 import org.onap.portalapp.portal.domain.UserRole;
79 import org.onap.portalapp.portal.domain.UserRoles;
80 import org.onap.portalapp.portal.ecomp.model.AppCatalogItem;
81 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
82 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
83 import org.onap.portalapp.portal.transport.EPAppsManualPreference;
84 import org.onap.portalapp.portal.transport.EPAppsSortPreference;
85 import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref;
86 import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
87 import org.onap.portalapp.portal.transport.FieldsValidator;
88 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
89 import org.onap.portalapp.portal.transport.LocalRole;
90 import org.onap.portalapp.portal.transport.OnboardingApp;
91 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
92 import org.onap.portalapp.portal.utils.EcompPortalUtils;
93 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
94 import org.onap.portalsdk.core.onboarding.ueb.Helper;
95 import org.onap.portalsdk.core.onboarding.ueb.TopicManager;
96 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
97 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
98 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
99 import org.onap.portalsdk.core.service.DataAccessService;
100 import org.onap.portalsdk.core.util.SystemProperties;
101 import org.springframework.beans.factory.annotation.Autowired;
102 import org.springframework.http.HttpEntity;
103 import org.springframework.http.HttpHeaders;
104 import org.springframework.http.HttpMethod;
105 import org.springframework.http.HttpStatus;
106 import org.springframework.http.ResponseEntity;
107 import org.springframework.web.client.HttpClientErrorException;
108 import org.springframework.web.client.RestTemplate;
110 import com.att.nsa.apiClient.http.HttpException;
111 import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
112 import com.att.nsa.cambria.client.CambriaClientBuilders;
113 import com.att.nsa.cambria.client.CambriaIdentityManager;
114 import com.att.nsa.cambria.client.CambriaTopicManager;
116 public class EPAppCommonServiceImpl implements EPAppService {
118 protected String ECOMP_APP_ID = "1";
119 protected String SUPER_ADMIN_ROLE_ID = "1";
120 protected String ACCOUNT_ADMIN_ROLE_ID = "999";
121 protected String RESTRICTED_APP_ROLE_ID = "900";
123 //private static final String urlField = "url";
124 private static final String nameSpaceField = "url";
126 private static final String nameField = "name";
128 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
131 private AdminRolesService adminRolesService;
133 protected SessionFactory sessionFactory;
135 private DataAccessService dataAccessService;
137 RestTemplate template = new RestTemplate();
140 private void init() {
141 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
142 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
143 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
144 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
147 public Boolean onboardingAppFieldsValidation(OnboardingApp onboardingApp) {
148 //FieldsValidator fieldsValidator = new FieldsValidator();
150 if ((!onboardingApp.restrictedApp) &&( onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.restrictedApp == null
151 || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.restUrl == null || onboardingApp.restUrl.length() == 0
152 || onboardingApp.username == null || onboardingApp.username.length() == 0
153 || onboardingApp.isOpen == null
154 || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID)))
155 // For a normal app (appType == PortalConstants.PortalAppId),
156 // these fields must be filled
158 // For a restricted app (appType==2), they will be empty.
159 || ((onboardingApp.restrictedApp) && (onboardingApp.name == null || onboardingApp.name.length() == 0
160 || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.isOpen == null))) {
167 private Boolean onboardingInactiveAppFieldsForValidation(OnboardingApp onboardingApp) {
168 if (onboardingApp.name == null || onboardingApp.name.length() == 0
169 || onboardingApp.isOpen == null) {
175 protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
176 FieldsValidator fieldsValidator = new FieldsValidator();
177 if (onboardingApp.isCentralAuth) {
178 if (!onboardingApp.isEnabled) {
179 if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
180 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
182 } else if (onboardingApp.isEnabled) {
183 if (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.nameSpace == null
184 || onboardingApp.nameSpace.length() == 0) {
185 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
189 if (!onboardingApp.isEnabled) {
190 if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
191 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
193 } else if (onboardingApp.isEnabled) {
194 if(onboardingApp.restrictedApp && onboardingAppFieldsValidation(onboardingApp) == false){
195 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
197 else if (!onboardingApp.restrictedApp && (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.appPassword == null
198 || onboardingApp.appPassword.length() == 0)) {
199 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
203 return fieldsValidator;
207 public List<EPApp> getUserAsAdminApps(EPUser user) {
208 if (adminRolesService.isAccountAdmin(user)) {
209 String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
210 + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
211 + " AND FN_APP.ENABLED = 'Y'";
214 @SuppressWarnings("unchecked")
215 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
217 } catch (Exception e) {
218 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
223 logger.error(EELFLoggerDelegate.errorLogger,
224 "getUserAsAdminApps: only Account Admin may invoke this function!");
225 return new ArrayList<EPApp>();
232 public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
233 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
234 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
235 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
236 + " AND FN_APP.ENABLED = 'Y'";
238 String sql = String.format(format, orgUserId);
242 @SuppressWarnings("unchecked")
243 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
245 } catch (Exception e) {
246 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
252 public List<EPApp> getAppsFullList() {
253 @SuppressWarnings("unchecked")
254 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
259 public List<EcompApp> getEcompAppAppsFullList() {
260 return transformAppsToEcompApps(getAppsFullList());
264 public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
265 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
266 for (EPApp app : appsList) {
267 EcompApp ecompApp = new EcompApp();
268 ecompApp.setId(app.getId());
269 ecompApp.setName(app.getName());
270 ecompApp.setImageUrl(app.getImageUrl());
271 ecompApp.setDescription(app.getDescription());
272 ecompApp.setNotes(app.getNotes());
273 ecompApp.setUrl(app.getUrl());
274 ecompApp.setAlternateUrl(app.getAlternateUrl());
275 ecompApp.setUebTopicName(app.getUebTopicName());
276 //ecompApp.setUebKey(app.getUebKey());
277 ecompApp.setUebSecret(app.getUebSecret());
278 ecompApp.setEnabled(app.getEnabled());
279 ecompApp.setCentralAuth(app.getCentralAuth());
280 ecompApp.setNameSpace(app.getNameSpace());
281 ecompApp.setRestrictedApp(app.isRestrictedApp());
282 ecompAppList.add(ecompApp);
288 public EPApp getApp(Long appId) {
290 return (EPApp) dataAccessService.getDomainObject(EPApp.class, appId, null);
291 } catch (Exception e) {
292 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
299 @SuppressWarnings("unchecked")
301 public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
303 if (adminRolesService.isAccountAdmin(user) && adminRolesService.isRoleAdmin(user)) {
304 final Map<String, Long> params = new HashMap<>();
305 params.put("userId", user.getId());
306 List applicationRoleswithAccountandRoleadmin = dataAccessService
307 .executeNamedQuery("getApplicationsofTheUserwithAdminAndRoleAdmin", params, null);
309 return applicationRoleswithAccountandRoleadmin;
310 } catch (Exception e) {
311 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
312 logger.error(EELFLoggerDelegate.errorLogger,
313 "Exception occurred while fetching the list of user who has type account and role approver "
320 if (adminRolesService.isAccountAdmin(user)) {
321 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 "
322 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
323 + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
324 String sql = String.format(format, user.getId());
327 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
328 } catch (Exception e) {
329 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
330 logger.error(EELFLoggerDelegate.errorLogger,
331 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
336 if (adminRolesService.isRoleAdmin(user)) {
337 final Map<String, Long> params = new HashMap<>();
338 params.put("userId", user.getId());
339 List applicationRoles = dataAccessService.executeNamedQuery("getApplicationsofTheUserContainsApprover",
343 return applicationRoles;
344 } catch (Exception e) {
345 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
346 logger.error(EELFLoggerDelegate.errorLogger,
347 "Exception occurred while fetching the list of user who has type approver "
354 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
355 // app.APP_REST_ENDPOINT <> ''";
357 return new ArrayList<AppIdAndNameTransportModel>();
361 public EPApp getAppDetail(String appName) {
362 final Map<String, String> params = new HashMap<String, String>();
364 params.put("appName", appName);
365 @SuppressWarnings("unchecked")
366 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
367 return (apps.size() > 0) ? apps.get(0) : null;
368 } catch(Exception e) {
369 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
375 public EPApp getAppDetailByAppName(String appName) {
376 final Map<String, String> params = new HashMap<String, String>();
378 params.put("appName", appName);
379 @SuppressWarnings("unchecked")
380 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getAppDetailsByAppName", params, null);
381 if (apps.size() > 0) {
382 EPApp app = apps.get(0);
383 if (!EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
384 app.setCentralAuth(false);
390 } catch (Exception e) {
391 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
396 @SuppressWarnings("unchecked")
398 public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
399 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
402 if (adminRolesService.isSuperAdmin(user)) {
403 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
404 + "where app.ENABLED = 'Y' AND app.app_type = 1";
406 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 "
407 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
408 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
410 sql = String.format(format, user.getId());
411 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
412 // app.APP_REST_ENDPOINT <> ''";
415 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
416 } catch (Exception e) {
417 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
418 logger.error(EELFLoggerDelegate.errorLogger,
419 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
422 return new ArrayList<AppIdAndNameTransportModel>();
425 protected void logQuery(String sql) {
426 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
429 public DataAccessService getDataAccessService() {
430 return dataAccessService;
433 public void setDataAccessService(DataAccessService dataAccessService) {
434 this.dataAccessService = dataAccessService;
437 @SuppressWarnings("unchecked")
439 public List<AdminUserApplications> getAppsAdmins() {
441 Map<String, String> params = new HashMap<>();
442 params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
443 List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
445 return aggregateRowsResultsByUserId(adminApps);
446 } catch (Exception e) {
447 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
452 private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
453 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
454 for (AdminUserApp app : adminApps) {
455 Long userId = app.getUser_Id();
456 if (adminUserApplications.get(userId) == null)
457 adminUserApplications.put(userId, new AdminUserApplications(app));
459 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
461 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
465 public List<AppsResponse> getAllApps(Boolean all) {
466 // If all is true, return both active and inactive apps. Otherwise, just
468 @SuppressWarnings("unchecked")
469 // Sort the list by application name so the drop-down looks pretty.
470 List<EPApp> apps = all
471 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
472 : (List<EPApp>) dataAccessService.getList(EPApp.class,
473 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
475 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
476 for (EPApp app : apps) {
477 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
484 public List<AppsResponse> getAllApplications(Boolean all) {
485 // If all is true, return both active and inactive apps. Otherwise, just
487 @SuppressWarnings("unchecked")
488 // Sort the list by application name so the drop-down looks pretty.
489 List<EPApp> apps = all
490 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
491 :dataAccessService.getList(EPApp.class, null);
493 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
494 for (EPApp app : apps) {
495 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
500 public UserRoles getUserProfile(String loginId) {
501 final Map<String, String> params = new HashMap<>();
502 params.put("org_user_id", loginId);
503 @SuppressWarnings("unchecked")
504 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
505 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
506 if (usersRolesList == null || usersRolesList.size() < 1)
509 return usersRolesList.get(0);
513 public UserRoles getUserProfileNormalized(EPUser user) {
515 UserRoles userAndRoles = getUserProfile(user.getLoginId());
516 // If no roles are defined, treat this user as a guest.
517 if (user.isGuest() || userAndRoles == null) {
518 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
520 UserRole userRole = new UserRole();
521 userRole.setUser_Id(user.getId());
522 userRole.setOrgUserId(user.getLoginId());
523 userRole.setFirstName(user.getFirstName());
524 userRole.setLastName(user.getLastName());
525 userRole.setRoleId(-1L);
526 userRole.setRoleName("Guest");
527 userRole.setUser_Id(-1L);
528 userAndRoles = new UserRoles(userRole);
534 protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
535 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
536 for (UserRole user : userRoleList) {
537 String orgUserId = user.getOrgUserId();
538 if (userRoles.get(orgUserId) == null)
539 userRoles.put(orgUserId, new UserRoles(user));
541 userRoles.get(orgUserId).addRole(user.getRoleName());
543 return new ArrayList<UserRoles>(userRoles.values());
546 private boolean isRestrictedApp(Long appId) {
547 EPApp app = getApp(appId);
548 return app.isRestrictedApp();
551 // For the functional menu edit
553 public List<LocalRole> getAppRoles(Long appId) {
555 if (isRestrictedApp(appId)) {
556 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
557 }else if(appId == 1){
558 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
560 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
563 @SuppressWarnings("unchecked")
564 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
568 protected String userAppsQuery(EPUser user) {
569 StringBuilder query = new StringBuilder();
570 if (adminRolesService.isSuperAdmin(user)) {
571 query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
573 query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
575 "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
576 query.append(" AND FN_APP.ENABLED = 'Y'");
578 return query.toString();
581 /*protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
582 FieldsValidator fieldsValidator = new FieldsValidator();
583 if(onboardingApp.isCentralAuth){
584 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
585 || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
586 || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
587 || (onboardingApp.id != null && ECOMP_APP_ID.equals(onboardingApp.id.toString()))
588 // For a normal app (appType == PortalConstants.PortalAppId),
589 // these fields must be filled
591 // For a restricted app (appType==2), they will be empty.
592 || ((!onboardingApp.restrictedApp) && (onboardingApp.myLoginsAppName == null
593 || onboardingApp.myLoginsAppName.length() == 0 || onboardingApp.myLoginsAppOwner == null
594 || onboardingApp.myLoginsAppOwner.length() == 0 || onboardingApp.username == null
595 || onboardingApp.username.length() == 0 ))) {
596 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
600 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
601 || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
602 || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
603 || (onboardingApp.id != null && ECOMP_APP_ID.equals(onboardingApp.id.toString()))
604 // For a normal app (appType == PortalConstants.PortalAppId),
605 // these fields must be filled
607 // For a restricted app (appType==2), they will be empty.
608 || ((!onboardingApp.restrictedApp) && (onboardingApp.myLoginsAppName == null
609 || onboardingApp.myLoginsAppName.length() == 0 || onboardingApp.myLoginsAppOwner == null
610 || onboardingApp.myLoginsAppOwner.length() == 0 || onboardingApp.username == null
611 || onboardingApp.username.length() == 0 || onboardingApp.appPassword == null
612 || onboardingApp.appPassword.length() == 0))) {
613 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
618 return fieldsValidator;
622 public List<EPApp> getUserApps(EPUser user) {
623 List<EPApp> openApps = getOpenApps();
625 if (user.isGuest()) {
628 String sql = userAppsQuery(user);
631 // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
632 List<EPApp> appsList = new ArrayList<>();
633 @SuppressWarnings("unchecked")
634 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
635 HashSet<EPApp> appSet = new HashSet<>();
636 for (EPApp app : adminApps) {
641 for (EPApp app : openApps) {
642 if (!appSet.contains(app))
651 public List<EPApp> getPersAdminApps(EPUser user) {
652 final Map<String, Long> params = new HashMap<>();
653 params.put("userId", user.getId());
654 // Named query is stored in EP.hbm.xml, mapped to EPApp
655 @SuppressWarnings("unchecked")
656 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
661 public List<EPApp> getPersUserApps(EPUser user) {
662 final Map<String, Long> params = new HashMap<>();
663 params.put("userId", user.getId());
664 // Named query is stored in EP.hbm.xml, mapped to EPApp
665 @SuppressWarnings("unchecked")
666 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
674 * org.onap.portalapp.portal.service.EPAppService#getAppCatalog(
675 * org.onap.portalapp.portal.domain.EPUser)
678 public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
679 final Map<String, Long> params = new HashMap<>();
680 params.put("userId", user.getId());
681 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
682 @SuppressWarnings("unchecked")
683 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
691 * org.onap.portalapp.portal.service.EPAppService#getAdminAppCatalog(
692 * org.onap.portalapp.portal.domain.EPUser)
695 public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
696 final Map<String, Long> params = new HashMap<>();
697 params.put("userId", user.getId());
698 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
699 @SuppressWarnings("unchecked")
700 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
704 private List<EPApp> getOpenApps() {
705 @SuppressWarnings("unchecked")
706 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
710 @SuppressWarnings("unchecked")
712 public List<EPApp> getAppsOrderByName(EPUser user) {
713 final Map<String, Long> params = new HashMap<>();
714 List<EPApp> sortedAppsByName = null;
716 if (adminRolesService.isSuperAdmin(user)) {
717 params.put("userId", user.getId());
718 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
720 params.put("userId", user.getId());
721 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
723 } catch (Exception e) {
724 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
726 return sortedAppsByName;
729 @SuppressWarnings("unchecked")
731 public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
733 final Map<String, Long> params = new HashMap<>();
734 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
735 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
737 if (adminRolesService.isSuperAdmin(user)) {
738 params.put("userId", user.getId());
739 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
741 params.put("userId", user.getId());
742 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
744 Set<String> epAppSet = new HashSet<String>();
745 for (EPApp eapp : sortedAppsByLastUsed)
746 if (!epAppSet.contains(eapp.getName())) {
747 finalsortedAppsByLastUsed.add(eapp);
748 epAppSet.add(eapp.getName());
751 } catch (Exception e) {
752 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
754 return finalsortedAppsByLastUsed;
757 @SuppressWarnings("unchecked")
759 public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
760 final Map<String, Long> params = new HashMap<>();
761 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
762 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
764 if (adminRolesService.isSuperAdmin(user)) {
765 params.put("userId", user.getId());
766 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
768 params.put("userId", user.getId());
769 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
771 Set<String> epAppSet = new HashSet<String>();
773 for (EPApp eapp : sortedAppsByMostUsed) {
774 if (!epAppSet.contains(eapp.getName())) {
775 finalsortedAppsByMostUsed.add(eapp);
776 epAppSet.add(eapp.getName());
779 } catch (Exception e) {
780 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
783 return finalsortedAppsByMostUsed;
787 * This Method retrieves the User Apps by Sort Manual Preference
789 * @param: user--contains LoggedIn User Data
791 @SuppressWarnings("unchecked")
793 public List<EPApp> getAppsOrderByManual(EPUser user) {
794 final Map<String, Long> params = new HashMap<>();
795 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
796 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
798 if (adminRolesService.isSuperAdmin(user)) {
799 params.put("userId", user.getId());
800 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
802 params.put("userId", user.getId());
803 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
805 Set<String> epAppSet = new HashSet<String>();
807 for (EPApp eapp : sortedAppsByManual) {
808 if (!epAppSet.contains(eapp.getName())) {
809 finalsortedAppsByManual.add(eapp);
810 epAppSet.add(eapp.getName());
813 } catch (Exception e) {
814 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
816 return finalsortedAppsByManual;
820 public List<OnboardingApp> getOnboardingApps() {
821 @SuppressWarnings("unchecked")
822 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
823 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
824 for (EPApp app : apps) {
825 OnboardingApp onboardingApp = new OnboardingApp();
826 app.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);//to hide password from get request
827 createOnboardingFromApp(app, onboardingApp);
828 onboardingAppsList.add(onboardingApp);
830 return onboardingAppsList;
833 @SuppressWarnings("unchecked")
835 public List<OnboardingApp> getAdminAppsOfUser(EPUser user) {
837 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
838 List<Integer> userAdminApps = new ArrayList<>();
839 final Map<String, Long> userParams = new HashMap<>();
840 userParams.put("userId", user.getId());
841 userAdminApps = dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
843 // userAdminApps.removeIf(x -> x == Integer.valueOf(ECOMP_APP_ID));
845 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size());
846 onboardingAppsList = getOnboardingApps();
848 final List<Integer> userAdminApps1 = userAdminApps;
849 List<OnboardingApp> userApplicationAdmins = onboardingAppsList.stream().filter(x -> userAdminApps1.contains((int) (long)x.id)).collect(Collectors.toList());
851 return userApplicationAdmins;
855 public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
856 @SuppressWarnings("unchecked")
857 List<EPApp> apps = dataAccessService.getList(EPApp.class,
858 " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
859 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
860 for (EPApp app : apps) {
861 OnboardingApp onboardingApp = new OnboardingApp();
862 app.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request
863 createOnboardingFromApp(app, onboardingApp);
864 onboardingAppsList.add(onboardingApp);
866 return onboardingAppsList;
869 @SuppressWarnings("unchecked")
870 private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
871 boolean duplicatedNameSpace = false;
872 boolean duplicatedName = false;
874 if (onboardingApp.id == null) {
875 List<Criterion> restrictionsList = new ArrayList<Criterion>();
876 Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);
877 Criterion nameSpaceCrit = null;
878 Criterion orCrit = null;
879 if (onboardingApp.isCentralAuth) {
880 nameSpaceCrit = Restrictions.eq("nameSpace", onboardingApp.nameSpace);
881 orCrit = Restrictions.or(nameCrit, nameSpaceCrit);
883 orCrit = Restrictions.or(nameCrit);
884 restrictionsList.add(orCrit);
885 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
887 List<Criterion> restrictionsList = new ArrayList<Criterion>();
888 Criterion idCrit =Restrictions.eq("id", onboardingApp.id);
889 Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);
890 Criterion nameSpaceCrit = null;
891 Criterion orCrit= null;
892 if (onboardingApp.isCentralAuth) {
893 nameSpaceCrit = Restrictions.eq("nameSpace",onboardingApp.nameSpace);
894 orCrit = Restrictions.or(idCrit, nameSpaceCrit, nameCrit);
897 orCrit = Restrictions.or(idCrit, nameCrit);
899 restrictionsList.add(orCrit);
900 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
903 for (EPApp app : apps) {
904 if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) {
907 if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
908 duplicatedName = true;
909 if (duplicatedName) {
913 if (!duplicatedNameSpace && app.getNameSpace().equalsIgnoreCase(onboardingApp.nameSpace)) {
914 duplicatedNameSpace = true;
915 if (duplicatedNameSpace) {
921 if (duplicatedNameSpace || duplicatedName) {
922 if (duplicatedNameSpace) {
923 fieldsValidator.addProblematicFieldName(nameSpaceField);
925 if (duplicatedName) {
926 fieldsValidator.addProblematicFieldName(nameField);
928 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
929 fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
934 public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
935 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
936 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
937 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
938 validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
940 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
941 if (modifiedOnboardingApp.id != null) {
942 updateApp(modifiedOnboardingApp.id, modifiedOnboardingApp, fieldsValidator, user);
944 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
947 return fieldsValidator;
951 public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
952 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
953 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
954 validateOnboardingApp(newOnboardingApp, fieldsValidator);
956 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
957 if (newOnboardingApp.id == null) {
958 updateApp(null, newOnboardingApp, fieldsValidator, user);
960 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
963 return fieldsValidator;
966 @SuppressWarnings("unchecked")
968 public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
969 FieldsValidator fieldsValidator = new FieldsValidator();
970 if (!adminRolesService.isSuperAdmin(user)) {
971 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
972 return fieldsValidator;
974 final Map<String, Long> params = new HashMap<>();
975 params.put("app_id", appid);
976 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
977 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
978 for(int i=0;i<EPUserAppRolesRequestList.size();i++)
980 dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
983 Session localSession = null;
984 Transaction transaction = null;
985 Boolean result = false;
987 localSession = sessionFactory.openSession();
988 transaction = localSession.beginTransaction();
990 // 1) Remove the URL for any functional menu item associated with
992 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
993 // Named query is stored in EP.hbm.xml, mapped to EPApp
994 dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
995 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted URL for any functional menu item associated with app");
997 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
998 // 2)Remove any favorites associated with a menu item that is
999 // associated with this app
1000 dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
1001 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
1003 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
1004 // 3)Remove all role, appid records from fn_menu_functional_role
1005 // that are associated with this app
1006 dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
1007 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
1009 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1010 // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
1011 // that are associated with this app
1012 dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
1013 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1015 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
1016 // 5)Remove all rolefunctions, appid records from ep_app_function
1017 // that are associated with this app
1018 dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
1019 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
1021 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
1022 // 6)Remove all records from fn_user_role associated with this app
1023 dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
1024 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
1026 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
1027 // 7)Remove any widgets associated with this app
1028 dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
1029 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
1031 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
1032 // 8)Remove any roles associated with this app
1033 dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
1034 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
1036 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
1037 // 9)Remove all records from fn_role associated with this app
1038 dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
1039 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
1041 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
1042 // 10)Remove app contact us entries
1043 dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
1044 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
1046 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
1047 // 11)Remove rows in the app personalization selection table
1048 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
1049 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
1051 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
1052 // 12)Remove rows in the app personalization sort table
1053 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
1054 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
1056 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
1057 // 13)Remove rows in the app personalization sort table
1058 dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
1059 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
1061 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
1062 // 14)Remove rows in the ep_web_analytics_source
1063 dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
1064 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
1066 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
1067 // 15)Delete the app
1068 dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
1069 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
1072 // 1) Remove the URL for any functional menu item associated with
1074 String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
1075 + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
1077 Query query = localSession.createSQLQuery(sql);
1078 query.executeUpdate();
1080 // Remove any favorites associated with a menu item that is
1081 // associated with this app
1082 sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
1083 + " where fn_menu_functional_roles.app_id='" + appid + "' "
1084 + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
1086 query = localSession.createSQLQuery(sql);
1087 query.executeUpdate();
1089 // Remove all role, appid records from fn_menu_functional_role
1090 // that are associated with this app
1091 sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
1093 query = localSession.createSQLQuery(sql);
1094 query.executeUpdate();
1097 // Remove all roles, rolefunctions, appid records from ep_app_role_function
1098 // that are associated with this app
1099 sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
1100 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1101 query = localSession.createSQLQuery(sql);
1102 query.executeUpdate();
1104 //Remove all rolefunctions, appid records from ep_app_function
1105 // that are associated with this app
1106 sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
1107 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1108 query = localSession.createSQLQuery(sql);
1109 query.executeUpdate();
1111 // Remove all records from fn_user_role associated with this app
1112 sql = "delete from fn_user_role where app_id='" + appid + "'";
1114 query = localSession.createSQLQuery(sql);
1115 query.executeUpdate();
1117 // Remove any widgets associated with this app
1118 sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
1120 query = localSession.createSQLQuery(sql);
1121 query.executeUpdate();
1123 // Remove any roles associated with this app
1124 sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
1125 + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
1127 query = localSession.createSQLQuery(sql);
1128 query.executeUpdate();
1130 // Remove all records from fn_role associated with this app
1131 sql = "delete from fn_role where app_id='" + appid + "'";
1133 query = localSession.createSQLQuery(sql);
1134 query.executeUpdate();
1136 // Remove app contact us entries
1137 sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
1139 query = localSession.createSQLQuery(sql);
1140 query.executeUpdate();
1142 // Remove rows in the app personalization selection table
1143 sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
1145 query = localSession.createSQLQuery(sql);
1146 query.executeUpdate();
1148 // Remove rows in the app personalization sort table
1149 sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
1151 query = localSession.createSQLQuery(sql);
1152 query.executeUpdate();
1154 // Remove rows in the app personalization sort table
1155 sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
1157 query = localSession.createSQLQuery(sql);
1158 query.executeUpdate();
1160 // Remove rows in the app personalization sort table
1161 sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
1163 query = localSession.createSQLQuery(sql);
1164 query.executeUpdate();
1167 sql = "delete from fn_app where app_id='" + appid + "'";
1169 query = localSession.createSQLQuery(sql);
1170 query.executeUpdate();
1172 transaction.commit();
1175 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
1176 } catch (Exception e) {
1177 logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
1178 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
1179 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
1181 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
1184 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1186 return fieldsValidator;
1189 private static Object syncRests = new Object();
1191 // An app has been enabled/disabled. Must enable/disable all associated
1192 // functional menu items.
1193 protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1194 String active_yn = enabled ? "Y" : "N";
1195 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1196 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1197 + " AND r.app_id = '" + appId + "' ";
1199 @SuppressWarnings("unchecked")
1200 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1201 for (FunctionalMenuItem menuItem : menuItems) {
1202 FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1204 myMenuItem.active_yn = active_yn;
1205 localSession.save(myMenuItem);
1209 // Attention! If (appId == null) we use this function to create application
1210 // otherwise we use it to modify existing application
1211 protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1212 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1213 // Separate out the code for a restricted app, since it doesn't need any
1215 if (onboardingApp.restrictedApp) {
1216 boolean result = false;
1217 Session localSession = null;
1218 Transaction transaction = null;
1220 localSession = sessionFactory.openSession();
1221 transaction = localSession.beginTransaction();
1223 if (appId == null) {
1226 app = (EPApp) localSession.get(EPApp.class, appId);
1227 if (app == null || app.getId() == null) { // App is already
1229 transaction.commit();
1230 localSession.close();
1231 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1235 createAppFromOnboarding(app, onboardingApp, localSession);
1236 localSession.saveOrUpdate(app);
1237 // Enable or disable all menu items associated with this app
1238 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1239 transaction.commit();
1241 } catch (Exception e) {
1242 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1243 EcompPortalUtils.rollbackTransaction(transaction,
1244 "updateApp rollback, exception = " + e.toString());
1246 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1249 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1253 updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1259 protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1261 synchronized (syncRests) {
1262 boolean result = false;
1263 Session localSession = null;
1264 Transaction transaction = null;
1266 localSession = sessionFactory.openSession();
1267 transaction = localSession.beginTransaction();
1269 if (appId == null) {
1272 * In the parent class, the UEB code is responsible for generating the
1273 * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1274 * may be used in future at which point we can just remove this method and
1275 * depend on parent class's method So, using UUID generator to generate the
1276 * unique key instead.
1278 String uuidStr = UUID.randomUUID().toString();
1279 String appKey = uuidStr;
1280 String appSecret = uuidStr;
1281 String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1282 onboardingApp.setUebTopicName(appMailboxName);
1283 onboardingApp.setUebKey(appKey);
1284 onboardingApp.setUebSecret(appSecret);
1286 app = (EPApp) localSession.get(EPApp.class, appId);
1287 if (app == null || app.getId() == null) {
1288 // App is already deleted!
1289 transaction.commit();
1290 localSession.close();
1291 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1295 logger.debug(EELFLoggerDelegate.debugLogger,
1296 "updateRestrictedApp: about to call createAppFromOnboarding");
1297 createAppFromOnboarding(app, onboardingApp, localSession);
1298 logger.debug(EELFLoggerDelegate.debugLogger,
1299 "updateRestrictedApp: finished calling createAppFromOnboarding");
1300 localSession.saveOrUpdate(app);
1301 logger.debug(EELFLoggerDelegate.debugLogger,
1302 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1303 // Enable or disable all menu items associated with this app
1304 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1305 logger.debug(EELFLoggerDelegate.debugLogger,
1306 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1307 transaction.commit();
1308 logger.debug(EELFLoggerDelegate.debugLogger,
1309 "updateRestrictedApp: finished calling transaction.commit");
1311 } catch (Exception e) {
1312 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1313 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1314 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1315 EcompPortalUtils.rollbackTransaction(transaction,
1316 "updateRestrictedApp rollback, exception = " + e.toString());
1318 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1321 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1328 protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1330 synchronized (syncRests) {
1331 boolean result = false;
1332 Session localSession = null;
1333 Transaction transaction = null;
1335 localSession = sessionFactory.openSession();
1336 transaction = localSession.beginTransaction();
1338 if (appId == null) {
1340 // -------------------------------------------------------------------------------------------
1341 // Register this App with the UEB communication server.
1343 // the App's unique mailbox/topic
1344 // name and keys to the FN_APP table. The App's mailbox
1346 // keys will be visible to the
1347 // admin on the ONAP portal.
1348 // -------------------------------------------------------------------------------------------
1349 TopicManager topicManager = new TopicManager() {
1351 EPAppCommonServiceImpl service;
1353 public void init(EPAppCommonServiceImpl _service) {
1357 public void createTopic(String key, String secret, String topicName,
1358 String topicDescription) throws HttpException, CambriaApiException, IOException {
1360 init(EPAppCommonServiceImpl.this);
1361 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1362 if (logger.isInfoEnabled()) {
1363 logger.info("==> createTopic");
1364 logger.info("topicName: " + topicName);
1365 logger.info("topicDescription: " + topicDescription);
1367 CambriaTopicManager tm = null;
1369 tm = service.getTopicManager(urlList, key, secret);
1370 } catch (Exception e) {
1371 logger.error("pub.build Exception ", e);
1372 throw new CambriaApiException(topicName);
1374 tm.createTopic(topicName, topicDescription, 1, 1);
1377 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1378 String topicName) throws HttpException, CambriaApiException, IOException {
1379 logger.info("==> addPublisher to topic " + topicName);
1380 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1381 CambriaTopicManager tm = null;
1383 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1384 } catch (Exception e) {
1385 logger.error("pub.build Exception ", e);
1386 throw new CambriaApiException(topicName);
1388 tm.allowProducer(topicName, publisherKey);
1392 final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1393 .usingHosts(Helper.uebUrlList()).build();
1394 com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1395 "ONAP Portal Owner");
1396 String appKey = credential.getApiKey();
1397 String appSecret = credential.getApiSecret();
1398 String appMailboxName = null;
1400 int maxNumAttemptsToCreateATopic = 3;
1401 boolean successfullyCreatedMailbox = false;
1402 for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1403 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1406 topicManager.createTopic(
1407 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1408 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1409 appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
1410 successfullyCreatedMailbox = true;
1411 logger.debug(EELFLoggerDelegate.debugLogger,
1412 "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
1413 logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
1414 + appSecret + " generated using = " + user.getEmail());
1416 } catch (HttpException e) {
1417 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1418 if (e.getStatusCode() == 409) {
1419 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1420 + " already exists. Will try using a different name", e);
1422 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1428 if (successfullyCreatedMailbox) {
1429 onboardingApp.setUebTopicName(appMailboxName);
1430 onboardingApp.setUebKey(appKey);
1431 onboardingApp.setUebSecret(appSecret);
1435 * EP is a publisher to this App's new mailbox
1437 topicManager.addPublisher(
1438 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1439 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1440 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1444 * This App is a subscriber of its own mailbox
1446 topicManager.addSubscriber(
1447 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1448 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1452 * This App is a publisher to EP
1454 topicManager.addPublisher(
1455 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1456 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1457 PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1458 } catch (HttpException | CambriaApiException | IOException e) {
1459 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1460 logger.error(EELFLoggerDelegate.errorLogger,
1461 "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1462 transaction.commit();
1463 localSession.close();
1464 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1468 transaction.commit();
1469 localSession.close();
1470 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1474 app = (EPApp) localSession.get(EPApp.class, appId);
1475 if (app == null || app.getId() == null) {
1476 // App is already deleted!
1477 transaction.commit();
1478 localSession.close();
1479 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1483 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1484 createAppFromOnboarding(app, onboardingApp, localSession);
1485 logger.debug(EELFLoggerDelegate.debugLogger,
1486 "LR: updateApp: finished calling createAppFromOnboarding");
1487 localSession.saveOrUpdate(app);
1488 logger.debug(EELFLoggerDelegate.debugLogger,
1489 "LR: updateApp: finished calling localSession.saveOrUpdate");
1490 // Enable or disable all menu items associated with this app
1491 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1492 logger.debug(EELFLoggerDelegate.debugLogger,
1493 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1494 transaction.commit();
1495 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1496 logger.debug(EELFLoggerDelegate.debugLogger,
1497 "LR: updateApp: finished calling epUebHelper.addPublisher");
1499 } catch (Exception e) {
1500 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1501 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1502 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1503 EcompPortalUtils.rollbackTransaction(transaction,
1504 "updateApp rollback, exception = " + e.toString());
1506 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1509 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1515 public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1516 throws GeneralSecurityException, Exception {
1517 throw new Exception("This method can only be invoked from child class");
1521 * Populates a transport model of the application from a database row model.
1522 * Leaves out the thumbnail because the FE fetches images via a different
1526 * Model of database row
1527 * @param onboardingApp
1528 * Model for transport as JSON
1531 public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1532 onboardingApp.id = app.getId();
1533 onboardingApp.name = app.getName();
1534 onboardingApp.imageUrl = app.getImageUrl();
1535 onboardingApp.description = app.getDescription();
1536 onboardingApp.notes = app.getNotes();
1537 onboardingApp.url = app.getUrl();
1538 onboardingApp.alternateUrl = app.getAlternateUrl();
1539 onboardingApp.restUrl = app.getAppRestEndpoint();
1540 onboardingApp.isOpen = app.getOpen();
1541 onboardingApp.isEnabled = app.getEnabled();
1542 onboardingApp.username = app.getUsername();
1543 onboardingApp.appPassword = (app.getAppPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) ? EPCommonSystemProperties.APP_DISPLAY_PASSWORD :decryptedPassword(app.getAppPassword(), app);
1544 onboardingApp.uebTopicName = app.getUebTopicName();
1545 onboardingApp.uebKey = app.getUebKey();
1546 onboardingApp.uebSecret = app.getUebSecret();
1547 onboardingApp.isCentralAuth = app.getCentralAuth();
1548 onboardingApp.nameSpace = app.getNameSpace();
1549 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1550 // if (app.getThumbnail() != null)
1551 // onboardingApp.thumbnail = new
1552 // String(Base64.getEncoder().encode(app.getThumbnail()));
1556 * Creates a database object for an application from an uploaded transport
1557 * model. Must decode the thumbnail, if any.
1560 * @param onboardingApp
1561 * @param localSession
1562 * @return The first argument.
1564 protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1565 app.setName(onboardingApp.name);
1566 app.setDescription(onboardingApp.description);
1567 app.setNotes(onboardingApp.notes);
1568 app.setUrl(onboardingApp.url);
1569 app.setAlternateUrl(onboardingApp.alternateUrl);
1570 app.setAppRestEndpoint(onboardingApp.restUrl);
1571 app.setOpen(onboardingApp.isOpen);
1572 app.setEnabled(onboardingApp.isEnabled);
1573 app.setUsername(onboardingApp.username);
1574 if(!onboardingApp.appPassword.equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1575 app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
1576 //app.setUebTopicName(onboardingApp.uebTopicName);
1577 app.setUebKey(onboardingApp.uebKey);
1578 app.setUebSecret(onboardingApp.uebSecret);
1579 app.setCentralAuth(onboardingApp.isCentralAuth);
1580 app.setNameSpace(onboardingApp.nameSpace);
1581 app.setRestrictedApp(onboardingApp.restrictedApp);
1582 if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
1583 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1584 String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
1585 logger.debug(EELFLoggerDelegate.debugLogger,
1586 "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1587 if (splitBase64Thumbnail.length > 1) {
1588 // This occurs when we have a new image, not an existing image
1589 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1590 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1591 // This is basically a boolean indicator that an image is
1593 app.setImageUrl(constructImageName(onboardingApp));
1594 app.setThumbnail(decodedImage);
1596 } else if (app.getThumbnail() != null && onboardingApp.imageLink == null) {
1597 // The thumbnail that came in from the json is empty; the previous
1598 // thumbnail is NOT empty. Must delete it.
1599 logger.debug(EELFLoggerDelegate.debugLogger,
1600 "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1601 app.setImageUrl(null);
1602 app.setThumbnail(null);
1604 logger.debug(EELFLoggerDelegate.debugLogger,
1605 "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1610 protected String constructImageName(OnboardingApp onboardingApp) {
1611 return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
1615 // Don't encrypt or decrypt the password if it is null or the empty string
1616 private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1618 if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) {
1620 result = CipherUtil.decryptPKC(encryptedAppPwd,
1621 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1622 } catch (Exception e) {
1623 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1629 protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1631 if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) {
1633 result = CipherUtil.encryptPKC(decryptedAppPwd,
1634 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1635 } catch (Exception e) {
1636 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1642 @SuppressWarnings("unchecked")
1644 public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1645 FieldsValidator fieldsValidator = new FieldsValidator();
1646 final Map<String, Long> params = new HashMap<>();
1647 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1650 params.put("userId", user.getId());
1651 epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1652 Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1653 for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1654 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1656 for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1657 if (epWidgetsManPref.getWidgetid() != null) {
1658 Long widgetid = epWidgetsManPref.getWidgetid();
1659 if (existingWidgetsIds.containsKey(widgetid)) {
1660 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1661 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1662 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1663 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1664 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1665 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1666 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1667 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1669 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1670 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1671 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1672 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1673 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1674 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1675 epWidgetsManualSort.setUserId(user.getId());
1676 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1678 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1681 } catch (Exception e) {
1682 logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1683 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1685 return fieldsValidator;
1688 @SuppressWarnings("unchecked")
1690 public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1691 FieldsValidator fieldsValidator = new FieldsValidator();
1692 final Map<String, Long> params = new HashMap<>();
1693 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1695 params.put("userId", user.getId());
1696 epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1697 Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1698 for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1699 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1701 for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1702 if (delEpWidgetsManPref.getWidgetid() != null) {
1703 Long widgetId = delEpWidgetsManPref.getWidgetid();
1704 if (existingWidgetIds.containsKey(widgetId)) {
1705 params.put("widgetId",widgetId);
1706 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1708 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1711 } catch (Exception e) {
1712 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1713 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1715 return fieldsValidator;
1719 * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1721 * @param: appsSortManual--contains User Apps Data
1723 * @param: user--contains LoggedIn User Data
1725 @SuppressWarnings("unchecked")
1727 public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1728 FieldsValidator fieldsValidator = new FieldsValidator();
1729 final Map<String, Long> params = new HashMap<>();
1730 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1733 params.put("userId", user.getId());
1734 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1735 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1736 for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1737 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1739 for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1740 if (epAppsManPref.getAppid() != null) {
1741 Long appid = epAppsManPref.getAppid();
1742 if (existingAppIds.containsKey(appid)) {
1743 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1745 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1746 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1747 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1748 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1750 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1751 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1753 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1754 epAppsManualSort.setUserId(user.getId());
1755 dataAccessService.saveDomainObject(epAppsManualSort, null);
1757 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1760 } catch (Exception e) {
1761 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1762 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1764 return fieldsValidator;
1770 * @see org.onap.portalapp.portal.service.EPAppService#
1771 * deleteUserAppSortManual(java.lang.String,
1772 * org.onap.portalapp.portal.domain.EPUser)
1774 @SuppressWarnings("unchecked")
1776 public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1777 FieldsValidator fieldsValidator = new FieldsValidator();
1778 final Map<String, Long> params = new HashMap<>();
1779 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1781 params.put("userId", user.getId());
1782 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1783 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1784 for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1785 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1787 if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1788 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1789 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1790 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1792 } catch (Exception e) {
1793 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1794 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1796 return fieldsValidator;
1799 @SuppressWarnings("unchecked")
1801 public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1802 FieldsValidator fieldsValidator = new FieldsValidator();
1803 final Map<String, Long> params = new HashMap<>();
1804 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1805 EPUserAppsSortPreference usrSortPr = null;
1807 params.put("userId", user.getId());
1808 epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1809 if (epSortTypes.size() == 0) {
1810 usrSortPr = new EPUserAppsSortPreference();
1811 usrSortPr.setUserId((int)(long)(user.getId()));
1812 usrSortPr.setSortPref(appsSortPreference.getValue());
1813 dataAccessService.saveDomainObject(usrSortPr, null);
1814 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1816 usrSortPr = epSortTypes.get(0);
1817 usrSortPr.setSortPref(appsSortPreference.getValue());
1818 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1819 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1820 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1821 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1823 } catch (Exception e) {
1824 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1825 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1827 return fieldsValidator;
1830 @SuppressWarnings("unchecked")
1832 public String getUserAppsSortTypePreference(EPUser user) {
1833 final Map<String, Long> params = new HashMap<>();
1834 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1836 params.put("userId", user.getId());
1837 userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1838 if (userSortPrefs.size() > 0)
1839 return userSortPrefs.get(0).getSortPref();
1842 } catch (Exception e) {
1843 logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1850 public List<EPApp> getUserRemoteApps(String id) {
1851 throw new RuntimeException(" Cannot be called from parent class");
1855 public UserRoles getUserProfileForLeftMenu(String loginId) {
1856 final Map<String, String> params = new HashMap<>();
1857 params.put("org_user_id", loginId);
1858 @SuppressWarnings("unchecked")
1859 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1860 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1861 if (usersRolesList == null || usersRolesList.size() < 1)
1864 return usersRolesList.get(0);
1869 public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1870 final Map<String, String> params = new HashMap<>();
1871 params.put("org_user_id", loginId);
1872 @SuppressWarnings("unchecked")
1873 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1874 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1875 if (usersRolesList == null || usersRolesList.size() < 1)
1878 return usersRolesList.get(0);
1882 public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1884 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1885 // If no roles are defined, treat this user as a guest.
1886 if (user.isGuest() || userAndRoles == null) {
1887 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1889 userAndRoles = createUserRoles(user);
1892 return userAndRoles;
1896 public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1898 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1899 // If no roles are defined, treat this user as a guest.
1900 if (user.isGuest() || userAndRoles == null) {
1901 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1903 userAndRoles = createUserRoles(user);
1906 return userAndRoles;
1910 public UserRoles createUserRoles(EPUser user)
1912 UserRole userRole = new UserRole();
1913 userRole.setUser_Id(user.getId());
1914 userRole.setOrgUserId(user.getLoginId());
1915 userRole.setFirstName(user.getFirstName());
1916 userRole.setLastName(user.getLastName());
1917 userRole.setRoleId(-1L);
1918 userRole.setRoleName("Guest");
1919 userRole.setUser_Id(-1L);
1920 UserRoles userAndRoles = new UserRoles(userRole);
1921 return userAndRoles;
1925 @SuppressWarnings("unused")
1927 public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception {
1928 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1929 HttpEntity<String> entity = new HttpEntity<>(headers);
1930 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace);
1931 ResponseEntity<String> response = null;
1934 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1935 + "nss/" + namespace, HttpMethod.GET, entity, String.class);
1936 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace ,
1937 response.getStatusCode().value());
1938 if (response.getStatusCode().value() == 200) {
1939 String res = response.getBody();
1940 JSONObject jsonObj = new JSONObject(res);
1941 JSONArray namespaceArray = jsonObj.getJSONArray("ns");
1942 if(!namespaceArray.getJSONObject(0).has("admin")){
1943 logger.error(EELFLoggerDelegate.errorLogger,
1944 "No admins are available for requested namespace:" + namespace);
1945 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1946 "Portal Mechid is not an admin of" + namespace);
1949 JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin");
1950 ArrayList<String> list = new ArrayList<String>();
1951 if (namespaceAdminArray != null) {
1952 int len = namespaceAdminArray.length();
1953 for (int i = 0; i < len; i++) {
1954 list.add(namespaceAdminArray.get(i).toString());
1957 logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list);
1958 final String userName = SystemProperties
1959 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
1960 boolean idExists = list.stream().anyMatch(t -> userName.equals(t));
1962 logger.error(EELFLoggerDelegate.errorLogger,
1963 "Portal mechid is not admin of requested namespace:" + namespace);
1964 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1965 "Portal Mechid is not an admin of" + namespace);
1969 } catch (HttpClientErrorException e) {
1970 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
1971 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());