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.KeyConstants;
98 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
99 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
100 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
101 import org.onap.portalsdk.core.service.DataAccessService;
102 import org.onap.portalsdk.core.util.SystemProperties;
103 import org.springframework.beans.factory.annotation.Autowired;
104 import org.springframework.http.HttpEntity;
105 import org.springframework.http.HttpHeaders;
106 import org.springframework.http.HttpMethod;
107 import org.springframework.http.HttpStatus;
108 import org.springframework.http.ResponseEntity;
109 import org.springframework.web.client.HttpClientErrorException;
110 import org.springframework.web.client.RestTemplate;
112 import com.att.nsa.apiClient.http.HttpException;
113 import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
114 import com.att.nsa.cambria.client.CambriaClientBuilders;
115 import com.att.nsa.cambria.client.CambriaIdentityManager;
116 import com.att.nsa.cambria.client.CambriaTopicManager;
118 public class EPAppCommonServiceImpl implements EPAppService {
120 protected String ECOMP_APP_ID = "1";
121 protected String SUPER_ADMIN_ROLE_ID = "1";
122 protected String ACCOUNT_ADMIN_ROLE_ID = "999";
123 protected String RESTRICTED_APP_ROLE_ID = "900";
125 //private static final String urlField = "url";
126 private static final String nameSpaceField = "url";
128 private static final String nameField = "name";
130 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
133 private AdminRolesService adminRolesService;
135 protected SessionFactory sessionFactory;
137 private DataAccessService dataAccessService;
139 RestTemplate template = new RestTemplate();
142 private void init() {
143 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
144 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
145 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
146 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
149 public Boolean onboardingAppFieldsValidation(OnboardingApp onboardingApp) {
150 //FieldsValidator fieldsValidator = new FieldsValidator();
152 if ((!onboardingApp.getRestrictedApp()) &&( onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0 || onboardingApp.getRestrictedApp() == null
153 || onboardingApp.getLandingPage() == null || onboardingApp.getLandingPage().length() == 0 || onboardingApp.getRestUrl() == null || onboardingApp.getRestUrl().length() == 0
154 || onboardingApp.getAppBasicAuthUsername() == null || onboardingApp.getAppBasicAuthUsername().length() == 0
155 || onboardingApp.getIsOpen() == null
156 || (onboardingApp.getId() != null && onboardingApp.getId().equals(ECOMP_APP_ID)))
157 // For a normal app (appType == PortalConstants.PortalAppId),
158 // these fields must be filled
160 // For a restricted app (appType==2), they will be empty.
161 || ((onboardingApp.getRestrictedApp()) && (onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0
162 || onboardingApp.getLandingPage() == null || onboardingApp.getLandingPage().length() == 0 || onboardingApp.getIsOpen() == null))) {
169 private Boolean onboardingInactiveAppFieldsForValidation(OnboardingApp onboardingApp) {
170 if (onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0
171 || onboardingApp.getIsOpen() == null) {
177 protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
178 FieldsValidator fieldsValidator = new FieldsValidator();
179 if (onboardingApp.getRolesInAAF()) {
180 if (!onboardingApp.getIsEnabled()) {
181 if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
182 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
184 } else if (onboardingApp.getIsEnabled()) {
185 if (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.getNameSpace() == null
186 || onboardingApp.getNameSpace().length() == 0) {
187 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
191 if (!onboardingApp.getIsEnabled()) {
192 if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
193 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
195 } else if (onboardingApp.getIsEnabled()) {
196 if(onboardingApp.getRestrictedApp() && onboardingAppFieldsValidation(onboardingApp) == false){
197 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
199 else if (!onboardingApp.getRestrictedApp() && (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.getAppBasicAuthPassword() == null
200 || onboardingApp.getAppBasicAuthPassword().length() == 0)) {
201 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
205 return fieldsValidator;
209 public List<EPApp> getUserAsAdminApps(EPUser user) {
210 if (adminRolesService.isAccountAdmin(user)) {
211 String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
212 + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
213 + " AND FN_APP.ENABLED = 'Y'";
216 @SuppressWarnings("unchecked")
217 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
219 } catch (Exception e) {
220 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
225 logger.error(EELFLoggerDelegate.errorLogger,
226 "getUserAsAdminApps: only Account Admin may invoke this function!");
227 return new ArrayList<EPApp>();
234 public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
235 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
236 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
237 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
238 + " AND FN_APP.ENABLED = 'Y'";
240 String sql = String.format(format, orgUserId);
244 @SuppressWarnings("unchecked")
245 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
247 } catch (Exception e) {
248 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
254 public List<EPApp> getAppsFullList() {
255 @SuppressWarnings("unchecked")
256 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
261 public List<EcompApp> getEcompAppAppsFullList() {
262 return transformAppsToEcompApps(getAppsFullList());
266 public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
267 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
268 for (EPApp app : appsList) {
269 EcompApp ecompApp = new EcompApp();
270 ecompApp.setId(app.getId());
271 ecompApp.setName(app.getName());
272 ecompApp.setImageUrl(app.getImageUrl());
273 ecompApp.setDescription(app.getAppDescription());
274 ecompApp.setNotes(app.getAppNotes());
275 ecompApp.setUrl(app.getLandingPage());
276 ecompApp.setAlternateUrl(app.getAlternateLandingPage());
277 ecompApp.setUebTopicName(app.getUebTopicName());
278 //ecompApp.setUebKey(app.getUebKey());
279 ecompApp.setUebSecret(app.getUebSecret());
280 ecompApp.setEnabled(app.getEnabled());
281 ecompApp.setCentralAuth(app.getRolesInAAF());
282 ecompApp.setNameSpace(app.getNameSpace());
283 ecompApp.setRestrictedApp(app.isRestrictedApp());
284 ecompAppList.add(ecompApp);
290 public EPApp getApp(Long appId) {
292 return (EPApp) dataAccessService.getDomainObject(EPApp.class, appId, null);
293 } catch (Exception e) {
294 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
301 @SuppressWarnings("unchecked")
303 public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
305 if (adminRolesService.isAccountAdmin(user) && adminRolesService.isRoleAdmin(user)) {
306 final Map<String, Long> params = new HashMap<>();
307 params.put("userId", user.getId());
308 List applicationRoleswithAccountandRoleadmin = dataAccessService
309 .executeNamedQuery("getApplicationsofTheUserwithAdminAndRoleAdmin", params, null);
311 return applicationRoleswithAccountandRoleadmin;
312 } catch (Exception e) {
313 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
314 logger.error(EELFLoggerDelegate.errorLogger,
315 "Exception occurred while fetching the list of user who has type account and role approver "
322 if (adminRolesService.isAccountAdmin(user)) {
323 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 "
324 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
325 + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
326 String sql = String.format(format, user.getId());
329 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
330 } catch (Exception e) {
331 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
332 logger.error(EELFLoggerDelegate.errorLogger,
333 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
338 if (adminRolesService.isRoleAdmin(user)) {
339 final Map<String, Long> params = new HashMap<>();
340 params.put("userId", user.getId());
341 List applicationRoles = dataAccessService.executeNamedQuery("getApplicationsofTheUserContainsApprover",
345 return applicationRoles;
346 } catch (Exception e) {
347 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
348 logger.error(EELFLoggerDelegate.errorLogger,
349 "Exception occurred while fetching the list of user who has type approver "
356 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
357 // app.APP_REST_ENDPOINT <> ''";
359 return new ArrayList<AppIdAndNameTransportModel>();
363 public EPApp getAppDetail(String appName) {
364 final Map<String, String> params = new HashMap<String, String>();
366 params.put("appName", appName);
367 @SuppressWarnings("unchecked")
368 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
369 return (apps.size() > 0) ? apps.get(0) : null;
370 } catch(Exception e) {
371 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
377 public EPApp getAppDetailByAppName(String appName) {
378 final Map<String, String> params = new HashMap<String, String>();
380 params.put("appName", appName);
381 @SuppressWarnings("unchecked")
382 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getAppDetailsByAppName", params, null);
383 if (apps.size() > 0) {
384 EPApp app = apps.get(0);
385 if (!EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
386 app.setRolesInAAF(false);
392 } catch (Exception e) {
393 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
398 @SuppressWarnings("unchecked")
400 public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
401 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
404 if (adminRolesService.isSuperAdmin(user)) {
405 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
406 + "where app.ENABLED = 'Y' AND app.app_type = 1";
408 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 "
409 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
410 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
412 sql = String.format(format, user.getId());
413 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
414 // app.APP_REST_ENDPOINT <> ''";
417 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
418 } catch (Exception e) {
419 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
420 logger.error(EELFLoggerDelegate.errorLogger,
421 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
424 return new ArrayList<AppIdAndNameTransportModel>();
427 protected void logQuery(String sql) {
428 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
431 public DataAccessService getDataAccessService() {
432 return dataAccessService;
435 public void setDataAccessService(DataAccessService dataAccessService) {
436 this.dataAccessService = dataAccessService;
439 @SuppressWarnings("unchecked")
441 public List<AdminUserApplications> getAppsAdmins() {
443 Map<String, String> params = new HashMap<>();
444 params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
445 List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
447 return aggregateRowsResultsByUserId(adminApps);
448 } catch (Exception e) {
449 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
454 private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
455 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
456 for (AdminUserApp app : adminApps) {
457 Long userId = app.getUser_Id();
458 if (adminUserApplications.get(userId) == null)
459 adminUserApplications.put(userId, new AdminUserApplications(app));
461 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
463 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
467 public List<AppsResponse> getAllApps(Boolean all) {
468 // If all is true, return both active and inactive apps. Otherwise, just
470 @SuppressWarnings("unchecked")
471 // Sort the list by application name so the drop-down looks pretty.
472 List<EPApp> apps = all
473 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
474 : (List<EPApp>) dataAccessService.getList(EPApp.class,
475 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
477 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
478 for (EPApp app : apps) {
479 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
486 public List<AppsResponse> getAllApplications(Boolean all) {
487 // If all is true, return both active and inactive apps. Otherwise, just
489 @SuppressWarnings("unchecked")
490 // Sort the list by application name so the drop-down looks pretty.
491 List<EPApp> apps = all
492 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
493 :dataAccessService.getList(EPApp.class, null);
495 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
496 for (EPApp app : apps) {
497 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
502 public UserRoles getUserProfile(String loginId) {
503 final Map<String, String> params = new HashMap<>();
504 params.put("org_user_id", loginId);
505 @SuppressWarnings("unchecked")
506 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
507 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
508 if (usersRolesList == null || usersRolesList.size() < 1)
511 return usersRolesList.get(0);
515 public UserRoles getUserProfileNormalized(EPUser user) {
517 UserRoles userAndRoles = getUserProfile(user.getLoginId());
518 // If no roles are defined, treat this user as a guest.
519 if (user.isGuest() || userAndRoles == null) {
520 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
522 UserRole userRole = new UserRole();
523 userRole.setUser_Id(user.getId());
524 userRole.setOrgUserId(user.getLoginId());
525 userRole.setFirstName(user.getFirstName());
526 userRole.setLastName(user.getLastName());
527 userRole.setRoleId(-1L);
528 userRole.setRoleName("Guest");
529 userRole.setUser_Id(-1L);
530 userAndRoles = new UserRoles(userRole);
536 protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
537 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
538 for (UserRole user : userRoleList) {
539 String orgUserId = user.getOrgUserId();
540 if (userRoles.get(orgUserId) == null)
541 userRoles.put(orgUserId, new UserRoles(user));
543 userRoles.get(orgUserId).addRole(user.getRoleName());
545 return new ArrayList<UserRoles>(userRoles.values());
548 private boolean isRestrictedApp(Long appId) {
549 EPApp app = getApp(appId);
550 return app.isRestrictedApp();
553 // For the functional menu edit
555 public List<LocalRole> getAppRoles(Long appId) {
557 if (isRestrictedApp(appId)) {
558 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
559 }else if(appId == 1){
560 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
562 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
565 @SuppressWarnings("unchecked")
566 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
570 protected String userAppsQuery(EPUser user) {
571 StringBuilder query = new StringBuilder();
572 if (adminRolesService.isSuperAdmin(user)) {
573 query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
575 query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
577 "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
578 query.append(" AND FN_APP.ENABLED = 'Y'");
580 return query.toString();
583 /*protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
584 FieldsValidator fieldsValidator = new FieldsValidator();
585 if(onboardingApp.isCentralAuth){
586 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
587 || onboardingApp.url.length() == 0 || onboardingApp.getRestrictedApp() == null
588 || onboardingApp.getIsOpen() == null || onboardingApp.getIsEnabled() == null
589 || (onboardingApp.getId() != null && ECOMP_APP_ID.equals(onboardingApp.getId().toString()))
590 // For a normal app (appType == PortalConstants.PortalAppId),
591 // these fields must be filled
593 // For a restricted app (appType==2), they will be empty.
594 || ((!onboardingApp.getRestrictedApp()) && (onboardingApp.myLoginsAppName == null
595 || onboardingApp.myLoginsAppName.length() == 0 || onboardingApp.myLoginsAppOwner == null
596 || onboardingApp.myLoginsAppOwner.length() == 0 || onboardingApp.username == null
597 || onboardingApp.username.length() == 0 ))) {
598 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
602 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
603 || onboardingApp.url.length() == 0 || onboardingApp.getRestrictedApp() == null
604 || onboardingApp.getIsOpen() == null || onboardingApp.getIsEnabled() == null
605 || (onboardingApp.getId() != null && ECOMP_APP_ID.equals(onboardingApp.getId().toString()))
606 // For a normal app (appType == PortalConstants.PortalAppId),
607 // these fields must be filled
609 // For a restricted app (appType==2), they will be empty.
610 || ((!onboardingApp.getRestrictedApp()) && (onboardingApp.myLoginsAppName == null
611 || onboardingApp.myLoginsAppName.length() == 0 || onboardingApp.myLoginsAppOwner == null
612 || onboardingApp.myLoginsAppOwner.length() == 0 || onboardingApp.username == null
613 || onboardingApp.username.length() == 0 || onboardingApp.appPassword == null
614 || onboardingApp.appPassword.length() == 0))) {
615 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
620 return fieldsValidator;
624 public List<EPApp> getUserApps(EPUser user) {
625 List<EPApp> openApps = getOpenApps();
627 if (user.isGuest()) {
630 String sql = userAppsQuery(user);
633 // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
634 List<EPApp> appsList = new ArrayList<>();
635 @SuppressWarnings("unchecked")
636 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
637 HashSet<EPApp> appSet = new HashSet<>();
638 for (EPApp app : adminApps) {
643 for (EPApp app : openApps) {
644 if (!appSet.contains(app))
653 public List<EPApp> getPersAdminApps(EPUser user) {
654 final Map<String, Long> params = new HashMap<>();
655 params.put("userId", user.getId());
656 // Named query is stored in EP.hbm.xml, mapped to EPApp
657 @SuppressWarnings("unchecked")
658 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
663 public List<EPApp> getPersUserApps(EPUser user) {
664 final Map<String, Long> params = new HashMap<>();
665 params.put("userId", user.getId());
666 // Named query is stored in EP.hbm.xml, mapped to EPApp
667 @SuppressWarnings("unchecked")
668 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
676 * org.onap.portalapp.portal.service.EPAppService#getAppCatalog(
677 * org.onap.portalapp.portal.domain.EPUser)
680 public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
681 final Map<String, Long> params = new HashMap<>();
682 params.put("userId", user.getId());
683 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
684 @SuppressWarnings("unchecked")
685 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
693 * org.onap.portalapp.portal.service.EPAppService#getAdminAppCatalog(
694 * org.onap.portalapp.portal.domain.EPUser)
697 public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
698 final Map<String, Long> params = new HashMap<>();
699 params.put("userId", user.getId());
700 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
701 @SuppressWarnings("unchecked")
702 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
706 private List<EPApp> getOpenApps() {
707 @SuppressWarnings("unchecked")
708 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
712 @SuppressWarnings("unchecked")
714 public List<EPApp> getAppsOrderByName(EPUser user) {
715 final Map<String, Long> params = new HashMap<>();
716 List<EPApp> sortedAppsByName = null;
718 if (adminRolesService.isSuperAdmin(user)) {
719 params.put("userId", user.getId());
720 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
722 params.put("userId", user.getId());
723 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
725 } catch (Exception e) {
726 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
728 return sortedAppsByName;
731 @SuppressWarnings("unchecked")
733 public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
735 final Map<String, Long> params = new HashMap<>();
736 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
737 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
739 if (adminRolesService.isSuperAdmin(user)) {
740 params.put("userId", user.getId());
741 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
743 params.put("userId", user.getId());
744 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
746 Set<String> epAppSet = new HashSet<String>();
747 for (EPApp eapp : sortedAppsByLastUsed)
748 if (!epAppSet.contains(eapp.getName())) {
749 finalsortedAppsByLastUsed.add(eapp);
750 epAppSet.add(eapp.getName());
753 } catch (Exception e) {
754 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
756 return finalsortedAppsByLastUsed;
759 @SuppressWarnings("unchecked")
761 public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
762 final Map<String, Long> params = new HashMap<>();
763 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
764 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
766 if (adminRolesService.isSuperAdmin(user)) {
767 params.put("userId", user.getId());
768 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
770 params.put("userId", user.getId());
771 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
773 Set<String> epAppSet = new HashSet<String>();
775 for (EPApp eapp : sortedAppsByMostUsed) {
776 if (!epAppSet.contains(eapp.getName())) {
777 finalsortedAppsByMostUsed.add(eapp);
778 epAppSet.add(eapp.getName());
781 } catch (Exception e) {
782 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
785 return finalsortedAppsByMostUsed;
789 * This Method retrieves the User Apps by Sort Manual Preference
791 * @param: user--contains LoggedIn User Data
793 @SuppressWarnings("unchecked")
795 public List<EPApp> getAppsOrderByManual(EPUser user) {
796 final Map<String, Long> params = new HashMap<>();
797 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
798 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
800 if (adminRolesService.isSuperAdmin(user)) {
801 params.put("userId", user.getId());
802 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
804 params.put("userId", user.getId());
805 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
807 Set<String> epAppSet = new HashSet<String>();
809 for (EPApp eapp : sortedAppsByManual) {
810 if (!epAppSet.contains(eapp.getName())) {
811 finalsortedAppsByManual.add(eapp);
812 epAppSet.add(eapp.getName());
815 } catch (Exception e) {
816 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
818 return finalsortedAppsByManual;
822 public List<OnboardingApp> getOnboardingApps() {
823 @SuppressWarnings("unchecked")
824 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
825 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
826 for (EPApp app : apps) {
827 OnboardingApp onboardingApp = new OnboardingApp();
828 app.setAppBasicAuthPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);//to hide password from get request
829 createOnboardingFromApp(app, onboardingApp);
830 onboardingAppsList.add(onboardingApp);
832 return onboardingAppsList;
835 @SuppressWarnings("unchecked")
837 public List<OnboardingApp> getAdminAppsOfUser(EPUser user) {
839 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
840 List<Integer> userAdminApps = new ArrayList<>();
841 final Map<String, Long> userParams = new HashMap<>();
842 userParams.put("userId", user.getId());
843 userAdminApps = dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
845 // userAdminApps.removeIf(x -> x == Integer.valueOf(ECOMP_APP_ID));
847 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size());
848 onboardingAppsList = getOnboardingApps();
850 final List<Integer> userAdminApps1 = userAdminApps;
851 List<OnboardingApp> userApplicationAdmins = onboardingAppsList.stream().filter(x -> userAdminApps1.contains((int) (long)x.getId())).collect(Collectors.toList());
853 return userApplicationAdmins;
857 public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
858 @SuppressWarnings("unchecked")
859 List<EPApp> apps = dataAccessService.getList(EPApp.class,
860 " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
861 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
862 for (EPApp app : apps) {
863 OnboardingApp onboardingApp = new OnboardingApp();
864 createOnboardingFromApp(app, onboardingApp);
865 onboardingAppsList.add(onboardingApp);
867 return onboardingAppsList;
870 @SuppressWarnings("unchecked")
871 private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
872 boolean duplicatedNameSpace = false;
873 boolean duplicatedName = false;
875 if (onboardingApp.getId() == null) {
876 List<Criterion> restrictionsList = new ArrayList<Criterion>();
877 Criterion nameCrit = Restrictions.eq("name",onboardingApp.getAppName());
878 Criterion nameSpaceCrit = null;
879 Criterion orCrit = null;
880 if (onboardingApp.getRolesInAAF()) {
881 nameSpaceCrit = Restrictions.eq("nameSpace", onboardingApp.getNameSpace());
882 orCrit = Restrictions.or(nameCrit, nameSpaceCrit);
884 orCrit = Restrictions.or(nameCrit);
885 restrictionsList.add(orCrit);
886 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
888 List<Criterion> restrictionsList = new ArrayList<Criterion>();
889 Criterion idCrit =Restrictions.eq("id", onboardingApp.getId());
890 Criterion nameCrit = Restrictions.eq("name",onboardingApp.getAppName());
891 Criterion nameSpaceCrit = null;
892 Criterion orCrit= null;
893 if (onboardingApp.getRolesInAAF()) {
894 nameSpaceCrit = Restrictions.eq("nameSpace",onboardingApp.getNameSpace());
895 orCrit = Restrictions.or(idCrit, nameSpaceCrit, nameCrit);
898 orCrit = Restrictions.or(idCrit, nameCrit);
900 restrictionsList.add(orCrit);
901 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
904 for (EPApp app : apps) {
905 if (onboardingApp.getId() != null && onboardingApp.getId().equals(app.getId())) {
908 if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.getAppName())) {
909 duplicatedName = true;
910 if (duplicatedName) {
914 if (!duplicatedNameSpace && app.getNameSpace().equalsIgnoreCase(onboardingApp.getNameSpace())) {
915 duplicatedNameSpace = true;
916 if (duplicatedNameSpace) {
922 if (duplicatedNameSpace || duplicatedName) {
923 if (duplicatedNameSpace) {
924 fieldsValidator.addProblematicFieldName(nameSpaceField);
926 if (duplicatedName) {
927 fieldsValidator.addProblematicFieldName(nameField);
929 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
930 fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
935 public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
936 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
937 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
938 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
939 validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
941 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
942 if (modifiedOnboardingApp.getId() != null) {
943 updateApp(modifiedOnboardingApp.getId(), modifiedOnboardingApp, fieldsValidator, user);
945 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
948 return fieldsValidator;
952 public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
953 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
954 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
955 validateOnboardingApp(newOnboardingApp, fieldsValidator);
957 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
958 if (newOnboardingApp.getId() == null) {
959 updateApp(null, newOnboardingApp, fieldsValidator, user);
961 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
964 return fieldsValidator;
967 @SuppressWarnings("unchecked")
969 public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
970 FieldsValidator fieldsValidator = new FieldsValidator();
971 if (!adminRolesService.isSuperAdmin(user)) {
972 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
973 return fieldsValidator;
975 final Map<String, Long> params = new HashMap<>();
976 params.put("app_id", appid);
977 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
978 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
979 for(int i=0;i<EPUserAppRolesRequestList.size();i++)
981 dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
984 Session localSession = null;
985 Transaction transaction = null;
986 Boolean result = false;
988 localSession = sessionFactory.openSession();
989 transaction = localSession.beginTransaction();
991 // 1) Remove the URL for any functional menu item associated with
993 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
994 // Named query is stored in EP.hbm.xml, mapped to EPApp
995 dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
996 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted URL for any functional menu item associated with app");
998 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
999 // 2)Remove any favorites associated with a menu item that is
1000 // associated with this app
1001 dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
1002 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
1004 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
1005 // 3)Remove all role, appid records from fn_menu_functional_role
1006 // that are associated with this app
1007 dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
1008 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
1010 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1011 // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
1012 // that are associated with this app
1013 dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
1014 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1016 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
1017 // 5)Remove all rolefunctions, appid records from ep_app_function
1018 // that are associated with this app
1019 dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
1020 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
1022 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
1023 // 6)Remove all records from fn_user_role associated with this app
1024 dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
1025 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
1027 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
1028 // 7)Remove any widgets associated with this app
1029 dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
1030 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
1032 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
1033 // 8)Remove any roles associated with this app
1034 dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
1035 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
1037 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
1038 // 9)Remove all records from fn_role associated with this app
1039 dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
1040 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
1042 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
1043 // 10)Remove app contact us entries
1044 dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
1045 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
1047 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
1048 // 11)Remove rows in the app personalization selection table
1049 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
1050 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
1052 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
1053 // 12)Remove rows in the app personalization sort table
1054 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
1055 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
1057 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
1058 // 13)Remove rows in the app personalization sort table
1059 dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
1060 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
1062 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
1063 // 14)Remove rows in the ep_web_analytics_source
1064 dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
1065 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
1067 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
1068 // 15)Delete the app
1069 dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
1070 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
1073 // 1) Remove the URL for any functional menu item associated with
1075 String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
1076 + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
1078 Query query = localSession.createSQLQuery(sql);
1079 query.executeUpdate();
1081 // Remove any favorites associated with a menu item that is
1082 // associated with this app
1083 sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
1084 + " where fn_menu_functional_roles.app_id='" + appid + "' "
1085 + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
1087 query = localSession.createSQLQuery(sql);
1088 query.executeUpdate();
1090 // Remove all role, appid records from fn_menu_functional_role
1091 // that are associated with this app
1092 sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
1094 query = localSession.createSQLQuery(sql);
1095 query.executeUpdate();
1098 // Remove all roles, rolefunctions, appid records from ep_app_role_function
1099 // that are associated with this app
1100 sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
1101 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1102 query = localSession.createSQLQuery(sql);
1103 query.executeUpdate();
1105 //Remove all rolefunctions, appid records from ep_app_function
1106 // that are associated with this app
1107 sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
1108 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1109 query = localSession.createSQLQuery(sql);
1110 query.executeUpdate();
1112 // Remove all records from fn_user_role associated with this app
1113 sql = "delete from fn_user_role where app_id='" + appid + "'";
1115 query = localSession.createSQLQuery(sql);
1116 query.executeUpdate();
1118 // Remove any widgets associated with this app
1119 sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
1121 query = localSession.createSQLQuery(sql);
1122 query.executeUpdate();
1124 // Remove any roles associated with this app
1125 sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
1126 + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
1128 query = localSession.createSQLQuery(sql);
1129 query.executeUpdate();
1131 // Remove all records from fn_role associated with this app
1132 sql = "delete from fn_role where app_id='" + appid + "'";
1134 query = localSession.createSQLQuery(sql);
1135 query.executeUpdate();
1137 // Remove app contact us entries
1138 sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
1140 query = localSession.createSQLQuery(sql);
1141 query.executeUpdate();
1143 // Remove rows in the app personalization selection table
1144 sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
1146 query = localSession.createSQLQuery(sql);
1147 query.executeUpdate();
1149 // Remove rows in the app personalization sort table
1150 sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
1152 query = localSession.createSQLQuery(sql);
1153 query.executeUpdate();
1155 // Remove rows in the app personalization sort table
1156 sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
1158 query = localSession.createSQLQuery(sql);
1159 query.executeUpdate();
1161 // Remove rows in the app personalization sort table
1162 sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
1164 query = localSession.createSQLQuery(sql);
1165 query.executeUpdate();
1168 sql = "delete from fn_app where app_id='" + appid + "'";
1170 query = localSession.createSQLQuery(sql);
1171 query.executeUpdate();
1173 transaction.commit();
1176 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
1177 } catch (Exception e) {
1178 logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
1179 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
1180 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
1182 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
1185 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1187 return fieldsValidator;
1190 private static Object syncRests = new Object();
1192 // An app has been enabled/disabled. Must enable/disable all associated
1193 // functional menu items.
1194 protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1195 String active_yn = enabled ? "Y" : "N";
1196 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1197 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1198 + " AND r.app_id = '" + appId + "' ";
1200 @SuppressWarnings("unchecked")
1201 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1202 for (FunctionalMenuItem menuItem : menuItems) {
1203 FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1205 myMenuItem.active_yn = active_yn;
1206 localSession.save(myMenuItem);
1210 // Attention! If (appId == null) we use this function to create application
1211 // otherwise we use it to modify existing application
1212 protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1213 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1214 // Separate out the code for a restricted app, since it doesn't need any
1216 if (Boolean.TRUE.equals(onboardingApp.getRestrictedApp())) {
1217 boolean result = false;
1218 Session localSession = null;
1219 Transaction transaction = null;
1221 localSession = sessionFactory.openSession();
1222 transaction = localSession.beginTransaction();
1224 if (appId == null) {
1227 app = (EPApp) localSession.get(EPApp.class, appId);
1228 if (app == null || app.getId() == null) { // App is already
1230 transaction.commit();
1231 localSession.close();
1232 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1236 createAppFromOnboarding(app, onboardingApp, localSession);
1237 localSession.saveOrUpdate(app);
1238 // Enable or disable all menu items associated with this app
1239 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1240 transaction.commit();
1242 } catch (Exception e) {
1243 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1244 EcompPortalUtils.rollbackTransaction(transaction,
1245 "updateApp rollback, exception = " + e.toString());
1247 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1250 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1254 updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1260 protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1262 synchronized (syncRests) {
1263 boolean result = false;
1264 Session localSession = null;
1265 Transaction transaction = null;
1267 localSession = sessionFactory.openSession();
1268 transaction = localSession.beginTransaction();
1270 if (appId == null) {
1273 * In the parent class, the UEB code is responsible for generating the
1274 * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1275 * may be used in future at which point we can just remove this method and
1276 * depend on parent class's method So, using UUID generator to generate the
1277 * unique key instead.
1279 String uuidStr = UUID.randomUUID().toString();
1280 String appKey = uuidStr;
1281 String appSecret = uuidStr;
1282 String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1283 onboardingApp.setUebTopicName(appMailboxName);
1284 onboardingApp.setUebKey(appKey);
1285 onboardingApp.setUebSecret(appSecret);
1287 app = (EPApp) localSession.get(EPApp.class, appId);
1288 if (app == null || app.getId() == null) {
1289 // App is already deleted!
1290 transaction.commit();
1291 localSession.close();
1292 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1296 logger.debug(EELFLoggerDelegate.debugLogger,
1297 "updateRestrictedApp: about to call createAppFromOnboarding");
1298 createAppFromOnboarding(app, onboardingApp, localSession);
1299 logger.debug(EELFLoggerDelegate.debugLogger,
1300 "updateRestrictedApp: finished calling createAppFromOnboarding");
1301 localSession.saveOrUpdate(app);
1302 logger.debug(EELFLoggerDelegate.debugLogger,
1303 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1304 // Enable or disable all menu items associated with this app
1305 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1306 logger.debug(EELFLoggerDelegate.debugLogger,
1307 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1308 transaction.commit();
1309 logger.debug(EELFLoggerDelegate.debugLogger,
1310 "updateRestrictedApp: finished calling transaction.commit");
1312 } catch (Exception e) {
1313 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1314 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1315 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1316 EcompPortalUtils.rollbackTransaction(transaction,
1317 "updateRestrictedApp rollback, exception = " + e.toString());
1319 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1322 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1329 protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1331 synchronized (syncRests) {
1332 boolean result = false;
1333 Session localSession = null;
1334 Transaction transaction = null;
1336 localSession = sessionFactory.openSession();
1337 transaction = localSession.beginTransaction();
1339 if (appId == null) {
1341 // -------------------------------------------------------------------------------------------
1342 // Register this App with the UEB communication server.
1344 // the App's unique mailbox/topic
1345 // name and keys to the FN_APP table. The App's mailbox
1347 // keys will be visible to the
1348 // admin on the ONAP portal.
1349 // -------------------------------------------------------------------------------------------
1350 TopicManager topicManager = new TopicManager() {
1352 EPAppCommonServiceImpl service;
1354 public void init(EPAppCommonServiceImpl _service) {
1358 public void createTopic(String key, String secret, String topicName,
1359 String topicDescription) throws HttpException, CambriaApiException, IOException {
1361 init(EPAppCommonServiceImpl.this);
1362 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1363 if (logger.isInfoEnabled()) {
1364 logger.info("==> createTopic");
1365 logger.info("topicName: " + topicName);
1366 logger.info("topicDescription: " + topicDescription);
1368 CambriaTopicManager tm = null;
1370 tm = service.getTopicManager(urlList, key, secret);
1371 } catch (Exception e) {
1372 logger.error("pub.build Exception ", e);
1373 throw new CambriaApiException(topicName);
1375 tm.createTopic(topicName, topicDescription, 1, 1);
1378 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1379 String topicName) throws HttpException, CambriaApiException, IOException {
1380 logger.info("==> addPublisher to topic " + topicName);
1381 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1382 CambriaTopicManager tm = null;
1384 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1385 } catch (Exception e) {
1386 logger.error("pub.build Exception ", e);
1387 throw new CambriaApiException(topicName);
1389 tm.allowProducer(topicName, publisherKey);
1393 final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1394 .usingHosts(Helper.uebUrlList()).build();
1395 com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1396 "ONAP Portal Owner");
1397 String appKey = credential.getApiKey();
1398 String appSecret = credential.getApiSecret();
1399 String appMailboxName = null;
1401 int maxNumAttemptsToCreateATopic = 3;
1402 boolean successfullyCreatedMailbox = false;
1403 for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1404 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1407 topicManager.createTopic(
1408 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1409 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1410 appMailboxName, "ECOMP outbox for app" + onboardingApp.getAppName());
1411 successfullyCreatedMailbox = true;
1412 logger.debug(EELFLoggerDelegate.debugLogger,
1413 "Successfully created " + appMailboxName + " for App " + onboardingApp.getAppName());
1414 logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
1415 + appSecret + " generated using = " + user.getEmail());
1417 } catch (HttpException e) {
1418 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1419 if (e.getStatusCode() == 409) {
1420 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1421 + " already exists. Will try using a different name", e);
1423 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1429 if (successfullyCreatedMailbox) {
1430 onboardingApp.setUebTopicName(appMailboxName);
1431 onboardingApp.setUebKey(appKey);
1432 onboardingApp.setUebSecret(appSecret);
1436 * EP is a publisher to this App's new mailbox
1438 topicManager.addPublisher(
1439 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1440 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1441 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1445 * This App is a subscriber of its own mailbox
1447 topicManager.addSubscriber(
1448 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1449 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1453 * This App is a publisher to EP
1455 topicManager.addPublisher(
1456 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1457 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1458 PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1459 } catch (HttpException | CambriaApiException | IOException e) {
1460 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1461 logger.error(EELFLoggerDelegate.errorLogger,
1462 "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1463 transaction.commit();
1464 localSession.close();
1465 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1469 transaction.commit();
1470 localSession.close();
1471 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1475 app = (EPApp) localSession.get(EPApp.class, appId);
1476 if (app == null || app.getId() == null) {
1477 // App is already deleted!
1478 transaction.commit();
1479 localSession.close();
1480 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1484 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1485 createAppFromOnboarding(app, onboardingApp, localSession);
1486 logger.debug(EELFLoggerDelegate.debugLogger,
1487 "LR: updateApp: finished calling createAppFromOnboarding");
1488 localSession.saveOrUpdate(app);
1489 logger.debug(EELFLoggerDelegate.debugLogger,
1490 "LR: updateApp: finished calling localSession.saveOrUpdate");
1491 // Enable or disable all menu items associated with this app
1492 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1493 logger.debug(EELFLoggerDelegate.debugLogger,
1494 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1495 transaction.commit();
1496 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1497 logger.debug(EELFLoggerDelegate.debugLogger,
1498 "LR: updateApp: finished calling epUebHelper.addPublisher");
1500 } catch (Exception e) {
1501 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1502 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1503 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1504 EcompPortalUtils.rollbackTransaction(transaction,
1505 "updateApp rollback, exception = " + e.toString());
1507 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1510 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1516 public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1517 throws GeneralSecurityException, Exception {
1518 throw new Exception("This method can only be invoked from child class");
1522 * Populates a transport model of the application from a database row model.
1523 * Leaves out the thumbnail because the FE fetches images via a different
1527 * Model of database row
1528 * @param onboardingApp
1529 * Model for transport as JSON
1532 public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1533 onboardingApp.setId(app.getId());
1534 onboardingApp.setAppName(app.getName());
1535 onboardingApp.setImageUrl(app.getImageUrl());
1536 onboardingApp.setAppDescription(app.getAppDescription());
1537 onboardingApp.setAppNotes(app.getAppNotes());
1538 onboardingApp.setLandingPage(app.getLandingPage());
1539 onboardingApp.setAlternateLandingPage(app.getAlternateLandingPage());
1540 onboardingApp.setRestUrl(app.getAppRestEndpoint());
1541 onboardingApp.setIsOpen(app.getOpen());
1542 onboardingApp.setIsEnabled(app.getEnabled());
1543 onboardingApp.setAppBasicAuthUsername(app.getAppBasicAuthUsername());
1545 String effectivePwd = null;
1546 if (app.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1547 effectivePwd = EPCommonSystemProperties.APP_DISPLAY_PASSWORD;
1549 effectivePwd = decryptedPassword(app.getAppBasicAuthPassword(), app);
1551 onboardingApp.setAppBasicAuthPassword(effectivePwd);
1552 onboardingApp.setUebTopicName(app.getUebTopicName());
1553 onboardingApp.setUebKey(app.getUebKey());
1554 onboardingApp.setUebSecret(app.getUebSecret());
1555 onboardingApp.setRolesInAAF(app.getRolesInAAF());
1556 onboardingApp.setNameSpace(app.getNameSpace());
1557 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1558 onboardingApp.setModeOfIntegration(app.getModeOfIntegration());
1559 onboardingApp.setAppAck(app.getAppAck());
1560 onboardingApp.setUsesCadi(app.getUsesCadi());
1561 onboardingApp.setApplicationType(app.getAppType().toString());
1565 * Creates a database object for an application from an uploaded transport
1566 * model. Must decode the thumbnail, if any.
1569 * @param onboardingApp
1570 * @param localSession
1571 * @return The first argument.
1573 protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1574 app.setName(onboardingApp.getAppName());
1575 app.setAppDescription(onboardingApp.getAppDescription());
1576 app.setAppNotes(onboardingApp.getAppNotes());
1577 app.setLandingPage(onboardingApp.getLandingPage());
1578 app.setAlternateLandingPage(onboardingApp.getAlternateLandingPage());
1579 app.setAppRestEndpoint(onboardingApp.getRestUrl());
1580 app.setOpen(onboardingApp.getIsOpen());
1581 app.setEnabled(onboardingApp.getIsEnabled());
1582 app.setAppBasicAuthUsername(onboardingApp.getAppBasicAuthUsername());
1583 if(!onboardingApp.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1584 app.setAppBasicAuthPassword(this.encryptedPassword(onboardingApp.getAppBasicAuthPassword(), app));
1585 //app.setUebTopicName(onboardingApp.uebTopicName);
1586 app.setUebKey(onboardingApp.getUebKey());
1587 app.setUebSecret(onboardingApp.getUebSecret());
1588 app.setRolesInAAF(onboardingApp.getRolesInAAF());
1589 app.setNameSpace(onboardingApp.getNameSpace());
1590 app.setAppType(new Integer(onboardingApp.getApplicationType()));
1591 app.setModeOfIntegration(onboardingApp.getModeOfIntegration());
1592 app.setAppAck(onboardingApp.getAppAck());
1593 app.setUsesCadi(onboardingApp.getUsesCadi());
1596 if (!StringUtils.isEmpty(onboardingApp.getThumbnail())) {
1597 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1598 String[] splitBase64Thumbnail = onboardingApp.getThumbnail().split("base64,");
1599 logger.debug(EELFLoggerDelegate.debugLogger,
1600 "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1601 if (splitBase64Thumbnail.length > 1) {
1602 // This occurs when we have a new image, not an existing image
1603 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1604 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1605 // This is basically a boolean indicator that an image is
1607 app.setImageUrl(constructImageName(onboardingApp));
1608 app.setThumbnail(decodedImage);
1610 } else if (app.getThumbnail() != null && onboardingApp.getImageLink() == null) {
1611 // The thumbnail that came in from the json is empty; the previous
1612 // thumbnail is NOT empty. Must delete it.
1613 logger.debug(EELFLoggerDelegate.debugLogger,
1614 "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1615 app.setImageUrl(null);
1616 app.setThumbnail(null);
1618 logger.debug(EELFLoggerDelegate.debugLogger,
1619 "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1624 protected String constructImageName(OnboardingApp onboardingApp) {
1625 return "portal_" + String.valueOf(onboardingApp.getLandingPage().hashCode() + "_" + (int) (Math.random() * 100000.0))
1629 // Don't encrypt or decrypt the password if it is null or the empty string
1630 private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1632 if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) {
1634 result = CipherUtil.decryptPKC(encryptedAppPwd,
1635 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1636 } catch (Exception e) {
1637 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1643 protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1645 if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) {
1647 result = CipherUtil.encryptPKC(decryptedAppPwd,
1648 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1649 } catch (Exception e) {
1650 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1656 @SuppressWarnings("unchecked")
1658 public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1659 FieldsValidator fieldsValidator = new FieldsValidator();
1660 final Map<String, Long> params = new HashMap<>();
1661 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1664 params.put("userId", user.getId());
1665 epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1666 Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1667 for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1668 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1670 for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1671 if (epWidgetsManPref.getWidgetid() != null) {
1672 Long widgetid = epWidgetsManPref.getWidgetid();
1673 if (existingWidgetsIds.containsKey(widgetid)) {
1674 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1675 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1676 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1677 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1678 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1679 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1680 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1681 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1683 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1684 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1685 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1686 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1687 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1688 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1689 epWidgetsManualSort.setUserId(user.getId());
1690 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1692 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1695 } catch (Exception e) {
1696 logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1697 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1699 return fieldsValidator;
1702 @SuppressWarnings("unchecked")
1704 public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1705 FieldsValidator fieldsValidator = new FieldsValidator();
1706 final Map<String, Long> params = new HashMap<>();
1707 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1709 params.put("userId", user.getId());
1710 epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1711 Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1712 for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1713 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1715 for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1716 if (delEpWidgetsManPref.getWidgetid() != null) {
1717 Long widgetId = delEpWidgetsManPref.getWidgetid();
1718 if (existingWidgetIds.containsKey(widgetId)) {
1719 params.put("widgetId",widgetId);
1720 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1722 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1725 } catch (Exception e) {
1726 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1727 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1729 return fieldsValidator;
1733 * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1735 * @param: appsSortManual--contains User Apps Data
1737 * @param: user--contains LoggedIn User Data
1739 @SuppressWarnings("unchecked")
1741 public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1742 FieldsValidator fieldsValidator = new FieldsValidator();
1743 final Map<String, Long> params = new HashMap<>();
1744 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1747 params.put("userId", user.getId());
1748 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1749 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1750 for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1751 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1753 for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1754 if (epAppsManPref.getAppid() != null) {
1755 Long appid = epAppsManPref.getAppid();
1756 if (existingAppIds.containsKey(appid)) {
1757 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1759 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1760 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1761 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1762 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1764 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1765 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1767 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1768 epAppsManualSort.setUserId(user.getId());
1769 dataAccessService.saveDomainObject(epAppsManualSort, null);
1771 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1774 } catch (Exception e) {
1775 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1776 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1778 return fieldsValidator;
1784 * @see org.onap.portalapp.portal.service.EPAppService#
1785 * deleteUserAppSortManual(java.lang.String,
1786 * org.onap.portalapp.portal.domain.EPUser)
1788 @SuppressWarnings("unchecked")
1790 public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1791 FieldsValidator fieldsValidator = new FieldsValidator();
1792 final Map<String, Long> params = new HashMap<>();
1793 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1795 params.put("userId", user.getId());
1796 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1797 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1798 for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1799 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1801 if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1802 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1803 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1804 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1806 } catch (Exception e) {
1807 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1808 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1810 return fieldsValidator;
1813 @SuppressWarnings("unchecked")
1815 public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1816 FieldsValidator fieldsValidator = new FieldsValidator();
1817 final Map<String, Long> params = new HashMap<>();
1818 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1819 EPUserAppsSortPreference usrSortPr = null;
1821 params.put("userId", user.getId());
1822 epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1823 if (epSortTypes.size() == 0) {
1824 usrSortPr = new EPUserAppsSortPreference();
1825 usrSortPr.setUserId((int)(long)(user.getId()));
1826 usrSortPr.setSortPref(appsSortPreference.getValue());
1827 dataAccessService.saveDomainObject(usrSortPr, null);
1828 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1830 usrSortPr = epSortTypes.get(0);
1831 usrSortPr.setSortPref(appsSortPreference.getValue());
1832 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1833 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1834 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1835 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1837 } catch (Exception e) {
1838 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1839 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1841 return fieldsValidator;
1844 @SuppressWarnings("unchecked")
1846 public String getUserAppsSortTypePreference(EPUser user) {
1847 final Map<String, Long> params = new HashMap<>();
1848 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1850 params.put("userId", user.getId());
1851 userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1852 if (userSortPrefs.size() > 0)
1853 return userSortPrefs.get(0).getSortPref();
1856 } catch (Exception e) {
1857 logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1864 public List<EPApp> getUserRemoteApps(String id) {
1865 throw new RuntimeException(" Cannot be called from parent class");
1869 public UserRoles getUserProfileForLeftMenu(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( "getUserRolesForLeftMenu", params, null);
1874 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1875 if (usersRolesList == null || usersRolesList.size() < 1)
1878 return usersRolesList.get(0);
1883 public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1884 final Map<String, String> params = new HashMap<>();
1885 params.put("org_user_id", loginId);
1886 @SuppressWarnings("unchecked")
1887 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1888 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1889 if (usersRolesList == null || usersRolesList.size() < 1)
1892 return usersRolesList.get(0);
1896 public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1898 UserRoles userAndRoles = getUserProfileForLeftMenu(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 getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1912 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1913 // If no roles are defined, treat this user as a guest.
1914 if (user.isGuest() || userAndRoles == null) {
1915 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1917 userAndRoles = createUserRoles(user);
1920 return userAndRoles;
1924 public UserRoles createUserRoles(EPUser user)
1926 UserRole userRole = new UserRole();
1927 userRole.setUser_Id(user.getId());
1928 userRole.setOrgUserId(user.getLoginId());
1929 userRole.setFirstName(user.getFirstName());
1930 userRole.setLastName(user.getLastName());
1931 userRole.setRoleId(-1L);
1932 userRole.setRoleName("Guest");
1933 userRole.setUser_Id(-1L);
1934 UserRoles userAndRoles = new UserRoles(userRole);
1935 return userAndRoles;
1939 @SuppressWarnings("unused")
1941 public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception {
1942 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1943 HttpEntity<String> entity = new HttpEntity<>(headers);
1944 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace);
1945 ResponseEntity<String> response = null;
1948 String namespaceUrl = SystemProperties.
1949 getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "nss/" + namespace;
1951 response = template.exchange(namespaceUrl, HttpMethod.GET, entity, String.class);
1952 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace ,
1953 response.getStatusCode().value());
1954 if (response.getStatusCode().value() == 200) {
1955 String res = response.getBody();
1956 JSONObject jsonObj = new JSONObject(res);
1957 JSONArray namespaceArray = jsonObj.getJSONArray("ns");
1958 if(!namespaceArray.getJSONObject(0).has("admin")){
1959 logger.error(EELFLoggerDelegate.errorLogger,
1960 "No admins are available for requested namespace:" + namespace);
1961 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1962 "Portal Mechid is not an admin of" + namespace);
1965 JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin");
1966 ArrayList<String> list = new ArrayList<String>();
1967 if (namespaceAdminArray != null) {
1968 int len = namespaceAdminArray.length();
1969 for (int i = 0; i < len; i++) {
1970 list.add(namespaceAdminArray.get(i).toString());
1973 logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list);
1974 final String userName = SystemProperties
1975 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
1976 boolean idExists = list.stream().anyMatch(t -> userName.equals(t));
1978 logger.error(EELFLoggerDelegate.errorLogger,
1979 "Portal mechid is not admin of requested namespace:" + namespace);
1980 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1981 "Portal Mechid is not an admin of" + namespace);
1985 } catch (HttpClientErrorException e) {
1986 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
1987 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());