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 app_type!= 3 and id!=" + ECOMP_APP_ID, null, null);
862 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
863 for (EPApp app : apps) {
864 OnboardingApp onboardingApp = new OnboardingApp();
865 createOnboardingFromApp(app, onboardingApp);
866 onboardingAppsList.add(onboardingApp);
868 return onboardingAppsList;
871 @SuppressWarnings("unchecked")
872 private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
873 boolean duplicatedNameSpace = false;
874 boolean duplicatedName = false;
876 if (onboardingApp.getId() == null) {
877 List<Criterion> restrictionsList = new ArrayList<Criterion>();
878 Criterion nameCrit = Restrictions.eq("name",onboardingApp.getAppName());
879 Criterion nameSpaceCrit = null;
880 Criterion orCrit = null;
881 if (onboardingApp.getRolesInAAF()) {
882 nameSpaceCrit = Restrictions.eq("nameSpace", onboardingApp.getNameSpace());
883 orCrit = Restrictions.or(nameCrit, nameSpaceCrit);
885 orCrit = Restrictions.or(nameCrit);
886 restrictionsList.add(orCrit);
887 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
889 List<Criterion> restrictionsList = new ArrayList<Criterion>();
890 Criterion idCrit =Restrictions.eq("id", onboardingApp.getId());
891 Criterion nameCrit = Restrictions.eq("name",onboardingApp.getAppName());
892 Criterion nameSpaceCrit = null;
893 Criterion orCrit= null;
894 if (onboardingApp.getRolesInAAF()) {
895 nameSpaceCrit = Restrictions.eq("nameSpace",onboardingApp.getNameSpace());
896 orCrit = Restrictions.or(idCrit, nameSpaceCrit, nameCrit);
899 orCrit = Restrictions.or(idCrit, nameCrit);
901 restrictionsList.add(orCrit);
902 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
905 for (EPApp app : apps) {
906 if (onboardingApp.getId() != null && onboardingApp.getId().equals(app.getId())) {
909 if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.getAppName())) {
910 duplicatedName = true;
911 if (duplicatedName) {
915 if (!duplicatedNameSpace && app.getNameSpace().equalsIgnoreCase(onboardingApp.getNameSpace())) {
916 duplicatedNameSpace = true;
917 if (duplicatedNameSpace) {
923 if (duplicatedNameSpace || duplicatedName) {
924 if (duplicatedNameSpace) {
925 fieldsValidator.addProblematicFieldName(nameSpaceField);
927 if (duplicatedName) {
928 fieldsValidator.addProblematicFieldName(nameField);
930 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
931 fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
936 public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
937 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
938 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
939 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
940 validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
942 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
943 if (modifiedOnboardingApp.getId() != null) {
944 updateApp(modifiedOnboardingApp.getId(), modifiedOnboardingApp, fieldsValidator, user);
946 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
949 return fieldsValidator;
953 public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
954 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
955 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
956 validateOnboardingApp(newOnboardingApp, fieldsValidator);
958 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
959 if (newOnboardingApp.getId() == null) {
960 updateApp(null, newOnboardingApp, fieldsValidator, user);
962 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
965 return fieldsValidator;
968 @SuppressWarnings("unchecked")
970 public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
971 FieldsValidator fieldsValidator = new FieldsValidator();
972 if (!adminRolesService.isSuperAdmin(user)) {
973 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
974 return fieldsValidator;
976 final Map<String, Long> params = new HashMap<>();
977 params.put("app_id", appid);
978 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
979 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
980 for(int i=0;i<EPUserAppRolesRequestList.size();i++)
982 dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
985 Session localSession = null;
986 Transaction transaction = null;
987 Boolean result = false;
989 localSession = sessionFactory.openSession();
990 transaction = localSession.beginTransaction();
992 // 1) Remove the URL for any functional menu item associated with
994 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
995 // Named query is stored in EP.hbm.xml, mapped to EPApp
996 dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
997 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted URL for any functional menu item associated with app");
999 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
1000 // 2)Remove any favorites associated with a menu item that is
1001 // associated with this app
1002 dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
1003 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
1005 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
1006 // 3)Remove all role, appid records from fn_menu_functional_role
1007 // that are associated with this app
1008 dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
1009 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
1011 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1012 // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
1013 // that are associated with this app
1014 dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
1015 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1017 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
1018 // 5)Remove all rolefunctions, appid records from ep_app_function
1019 // that are associated with this app
1020 dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
1021 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
1023 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
1024 // 6)Remove all records from fn_user_role associated with this app
1025 dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
1026 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
1028 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
1029 // 7)Remove any widgets associated with this app
1030 dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
1031 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
1033 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
1034 // 8)Remove any roles associated with this app
1035 dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
1036 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
1038 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
1039 // 9)Remove all records from fn_role associated with this app
1040 dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
1041 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
1043 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
1044 // 10)Remove app contact us entries
1045 dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
1046 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
1048 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
1049 // 11)Remove rows in the app personalization selection table
1050 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
1051 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
1053 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
1054 // 12)Remove rows in the app personalization sort table
1055 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
1056 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
1058 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
1059 // 13)Remove rows in the app personalization sort table
1060 dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
1061 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
1063 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
1064 // 14)Remove rows in the ep_web_analytics_source
1065 dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
1066 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
1068 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
1069 // 15)Delete the app
1070 dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
1071 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
1074 // 1) Remove the URL for any functional menu item associated with
1076 String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
1077 + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
1079 Query query = localSession.createSQLQuery(sql);
1080 query.executeUpdate();
1082 // Remove any favorites associated with a menu item that is
1083 // associated with this app
1084 sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
1085 + " where fn_menu_functional_roles.app_id='" + appid + "' "
1086 + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
1088 query = localSession.createSQLQuery(sql);
1089 query.executeUpdate();
1091 // Remove all role, appid records from fn_menu_functional_role
1092 // that are associated with this app
1093 sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
1095 query = localSession.createSQLQuery(sql);
1096 query.executeUpdate();
1099 // Remove all roles, rolefunctions, appid records from ep_app_role_function
1100 // that are associated with this app
1101 sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
1102 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1103 query = localSession.createSQLQuery(sql);
1104 query.executeUpdate();
1106 //Remove all rolefunctions, appid records from ep_app_function
1107 // that are associated with this app
1108 sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
1109 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1110 query = localSession.createSQLQuery(sql);
1111 query.executeUpdate();
1113 // Remove all records from fn_user_role associated with this app
1114 sql = "delete from fn_user_role where app_id='" + appid + "'";
1116 query = localSession.createSQLQuery(sql);
1117 query.executeUpdate();
1119 // Remove any widgets associated with this app
1120 sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
1122 query = localSession.createSQLQuery(sql);
1123 query.executeUpdate();
1125 // Remove any roles associated with this app
1126 sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
1127 + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
1129 query = localSession.createSQLQuery(sql);
1130 query.executeUpdate();
1132 // Remove all records from fn_role associated with this app
1133 sql = "delete from fn_role where app_id='" + appid + "'";
1135 query = localSession.createSQLQuery(sql);
1136 query.executeUpdate();
1138 // Remove app contact us entries
1139 sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
1141 query = localSession.createSQLQuery(sql);
1142 query.executeUpdate();
1144 // Remove rows in the app personalization selection table
1145 sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
1147 query = localSession.createSQLQuery(sql);
1148 query.executeUpdate();
1150 // Remove rows in the app personalization sort table
1151 sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
1153 query = localSession.createSQLQuery(sql);
1154 query.executeUpdate();
1156 // Remove rows in the app personalization sort table
1157 sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
1159 query = localSession.createSQLQuery(sql);
1160 query.executeUpdate();
1162 // Remove rows in the app personalization sort table
1163 sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
1165 query = localSession.createSQLQuery(sql);
1166 query.executeUpdate();
1169 sql = "delete from fn_app where app_id='" + appid + "'";
1171 query = localSession.createSQLQuery(sql);
1172 query.executeUpdate();
1174 transaction.commit();
1177 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
1178 } catch (Exception e) {
1179 logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
1180 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
1181 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
1183 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
1186 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1188 return fieldsValidator;
1191 private static Object syncRests = new Object();
1193 // An app has been enabled/disabled. Must enable/disable all associated
1194 // functional menu items.
1195 protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1196 String active_yn = enabled ? "Y" : "N";
1197 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1198 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1199 + " AND r.app_id = '" + appId + "' ";
1201 @SuppressWarnings("unchecked")
1202 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1203 for (FunctionalMenuItem menuItem : menuItems) {
1204 FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1206 myMenuItem.active_yn = active_yn;
1207 localSession.save(myMenuItem);
1211 // Attention! If (appId == null) we use this function to create application
1212 // otherwise we use it to modify existing application
1213 protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1214 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1215 // Separate out the code for a restricted app, since it doesn't need any
1217 if (Boolean.TRUE.equals(onboardingApp.getRestrictedApp())) {
1218 boolean result = false;
1219 Session localSession = null;
1220 Transaction transaction = null;
1222 localSession = sessionFactory.openSession();
1223 transaction = localSession.beginTransaction();
1225 if (appId == null) {
1228 app = (EPApp) localSession.get(EPApp.class, appId);
1229 if (app == null || app.getId() == null) { // App is already
1231 transaction.commit();
1232 localSession.close();
1233 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1237 createAppFromOnboarding(app, onboardingApp, localSession);
1238 localSession.saveOrUpdate(app);
1239 // Enable or disable all menu items associated with this app
1240 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1241 transaction.commit();
1243 } catch (Exception e) {
1244 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1245 EcompPortalUtils.rollbackTransaction(transaction,
1246 "updateApp rollback, exception = " + e.toString());
1248 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1251 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1255 updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1261 protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1263 synchronized (syncRests) {
1264 boolean result = false;
1265 Session localSession = null;
1266 Transaction transaction = null;
1268 localSession = sessionFactory.openSession();
1269 transaction = localSession.beginTransaction();
1271 if (appId == null) {
1274 * In the parent class, the UEB code is responsible for generating the
1275 * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1276 * may be used in future at which point we can just remove this method and
1277 * depend on parent class's method So, using UUID generator to generate the
1278 * unique key instead.
1280 String uuidStr = UUID.randomUUID().toString();
1281 String appKey = uuidStr;
1282 String appSecret = uuidStr;
1283 String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1284 onboardingApp.setUebTopicName(appMailboxName);
1285 onboardingApp.setUebKey(appKey);
1286 onboardingApp.setUebSecret(appSecret);
1288 app = (EPApp) localSession.get(EPApp.class, appId);
1289 if (app == null || app.getId() == null) {
1290 // App is already deleted!
1291 transaction.commit();
1292 localSession.close();
1293 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1297 logger.debug(EELFLoggerDelegate.debugLogger,
1298 "updateRestrictedApp: about to call createAppFromOnboarding");
1299 createAppFromOnboarding(app, onboardingApp, localSession);
1300 logger.debug(EELFLoggerDelegate.debugLogger,
1301 "updateRestrictedApp: finished calling createAppFromOnboarding");
1302 localSession.saveOrUpdate(app);
1303 logger.debug(EELFLoggerDelegate.debugLogger,
1304 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1305 // Enable or disable all menu items associated with this app
1306 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1307 logger.debug(EELFLoggerDelegate.debugLogger,
1308 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1309 transaction.commit();
1310 logger.debug(EELFLoggerDelegate.debugLogger,
1311 "updateRestrictedApp: finished calling transaction.commit");
1313 } catch (Exception e) {
1314 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1315 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1316 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1317 EcompPortalUtils.rollbackTransaction(transaction,
1318 "updateRestrictedApp rollback, exception = " + e.toString());
1320 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1323 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1330 protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1332 synchronized (syncRests) {
1333 boolean result = false;
1334 Session localSession = null;
1335 Transaction transaction = null;
1337 localSession = sessionFactory.openSession();
1338 transaction = localSession.beginTransaction();
1340 if (appId == null) {
1342 // -------------------------------------------------------------------------------------------
1343 // Register this App with the UEB communication server.
1345 // the App's unique mailbox/topic
1346 // name and keys to the FN_APP table. The App's mailbox
1348 // keys will be visible to the
1349 // admin on the ONAP portal.
1350 // -------------------------------------------------------------------------------------------
1351 TopicManager topicManager = new TopicManager() {
1353 EPAppCommonServiceImpl service;
1355 public void init(EPAppCommonServiceImpl _service) {
1359 public void createTopic(String key, String secret, String topicName,
1360 String topicDescription) throws HttpException, CambriaApiException, IOException {
1362 init(EPAppCommonServiceImpl.this);
1363 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1364 if (logger.isInfoEnabled()) {
1365 logger.info("==> createTopic");
1366 logger.info("topicName: " + topicName);
1367 logger.info("topicDescription: " + topicDescription);
1369 CambriaTopicManager tm = null;
1371 tm = service.getTopicManager(urlList, key, secret);
1372 } catch (Exception e) {
1373 logger.error("pub.build Exception ", e);
1374 throw new CambriaApiException(topicName);
1376 tm.createTopic(topicName, topicDescription, 1, 1);
1379 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1380 String topicName) throws HttpException, CambriaApiException, IOException {
1381 logger.info("==> addPublisher to topic " + topicName);
1382 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1383 CambriaTopicManager tm = null;
1385 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1386 } catch (Exception e) {
1387 logger.error("pub.build Exception ", e);
1388 throw new CambriaApiException(topicName);
1390 tm.allowProducer(topicName, publisherKey);
1394 final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1395 .usingHosts(Helper.uebUrlList()).build();
1396 com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1397 "ONAP Portal Owner");
1398 String appKey = credential.getApiKey();
1399 String appSecret = credential.getApiSecret();
1400 String appMailboxName = null;
1402 int maxNumAttemptsToCreateATopic = 3;
1403 boolean successfullyCreatedMailbox = false;
1404 for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1405 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1408 topicManager.createTopic(
1409 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1410 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1411 appMailboxName, "ECOMP outbox for app" + onboardingApp.getAppName());
1412 successfullyCreatedMailbox = true;
1413 logger.debug(EELFLoggerDelegate.debugLogger,
1414 "Successfully created " + appMailboxName + " for App " + onboardingApp.getAppName());
1415 logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
1416 + appSecret + " generated using = " + user.getEmail());
1418 } catch (HttpException e) {
1419 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1420 if (e.getStatusCode() == 409) {
1421 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1422 + " already exists. Will try using a different name", e);
1424 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1430 if (successfullyCreatedMailbox) {
1431 onboardingApp.setUebTopicName(appMailboxName);
1432 onboardingApp.setUebKey(appKey);
1433 onboardingApp.setUebSecret(appSecret);
1437 * EP is a publisher to this App's new mailbox
1439 topicManager.addPublisher(
1440 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1441 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1442 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1446 * This App is a subscriber of its own mailbox
1448 topicManager.addSubscriber(
1449 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1450 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1454 * This App is a publisher to EP
1456 topicManager.addPublisher(
1457 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1458 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1459 PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1460 } catch (HttpException | CambriaApiException | IOException e) {
1461 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1462 logger.error(EELFLoggerDelegate.errorLogger,
1463 "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1464 transaction.commit();
1465 localSession.close();
1466 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1470 transaction.commit();
1471 localSession.close();
1472 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1476 app = (EPApp) localSession.get(EPApp.class, appId);
1477 if (app == null || app.getId() == null) {
1478 // App is already deleted!
1479 transaction.commit();
1480 localSession.close();
1481 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1485 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1486 createAppFromOnboarding(app, onboardingApp, localSession);
1487 logger.debug(EELFLoggerDelegate.debugLogger,
1488 "LR: updateApp: finished calling createAppFromOnboarding");
1489 localSession.saveOrUpdate(app);
1490 logger.debug(EELFLoggerDelegate.debugLogger,
1491 "LR: updateApp: finished calling localSession.saveOrUpdate");
1492 // Enable or disable all menu items associated with this app
1493 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1494 logger.debug(EELFLoggerDelegate.debugLogger,
1495 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1496 transaction.commit();
1497 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1498 logger.debug(EELFLoggerDelegate.debugLogger,
1499 "LR: updateApp: finished calling epUebHelper.addPublisher");
1501 } catch (Exception e) {
1502 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1503 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1504 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1505 EcompPortalUtils.rollbackTransaction(transaction,
1506 "updateApp rollback, exception = " + e.toString());
1508 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1511 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1517 public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1518 throws GeneralSecurityException, Exception {
1519 throw new Exception("This method can only be invoked from child class");
1523 * Populates a transport model of the application from a database row model.
1524 * Leaves out the thumbnail because the FE fetches images via a different
1528 * Model of database row
1529 * @param onboardingApp
1530 * Model for transport as JSON
1533 public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1534 onboardingApp.setId(app.getId());
1535 onboardingApp.setAppName(app.getName());
1536 onboardingApp.setImageUrl(app.getImageUrl());
1537 onboardingApp.setAppDescription(app.getAppDescription());
1538 onboardingApp.setAppNotes(app.getAppNotes());
1539 onboardingApp.setLandingPage(app.getLandingPage());
1540 onboardingApp.setAlternateLandingPage(app.getAlternateLandingPage());
1541 onboardingApp.setRestUrl(app.getAppRestEndpoint());
1542 onboardingApp.setIsOpen(app.getOpen());
1543 onboardingApp.setIsEnabled(app.getEnabled());
1544 onboardingApp.setAppBasicAuthUsername(app.getAppBasicAuthUsername());
1546 String effectivePwd = null;
1547 if (app.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1548 effectivePwd = EPCommonSystemProperties.APP_DISPLAY_PASSWORD;
1550 effectivePwd = decryptedPassword(app.getAppBasicAuthPassword(), app);
1552 onboardingApp.setAppBasicAuthPassword(effectivePwd);
1553 onboardingApp.setUebTopicName(app.getUebTopicName());
1554 onboardingApp.setUebKey(app.getUebKey());
1555 onboardingApp.setUebSecret(app.getUebSecret());
1556 onboardingApp.setRolesInAAF(app.getRolesInAAF());
1557 onboardingApp.setNameSpace(app.getNameSpace());
1558 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1559 onboardingApp.setModeOfIntegration(app.getModeOfIntegration());
1560 onboardingApp.setAppAck(app.getAppAck());
1561 onboardingApp.setUsesCadi(app.getUsesCadi());
1562 onboardingApp.setApplicationType(app.getAppType().toString());
1566 * Creates a database object for an application from an uploaded transport
1567 * model. Must decode the thumbnail, if any.
1570 * @param onboardingApp
1571 * @param localSession
1572 * @return The first argument.
1574 protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1575 app.setName(onboardingApp.getAppName());
1576 app.setAppDescription(onboardingApp.getAppDescription());
1577 app.setAppNotes(onboardingApp.getAppNotes());
1578 app.setLandingPage(onboardingApp.getLandingPage());
1579 app.setAlternateLandingPage(onboardingApp.getAlternateLandingPage());
1580 app.setAppRestEndpoint(onboardingApp.getRestUrl());
1581 app.setOpen(onboardingApp.getIsOpen());
1582 app.setEnabled(onboardingApp.getIsEnabled());
1583 app.setAppBasicAuthUsername(onboardingApp.getAppBasicAuthUsername());
1584 if(!onboardingApp.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1585 app.setAppBasicAuthPassword(this.encryptedPassword(onboardingApp.getAppBasicAuthPassword(), app));
1586 //app.setUebTopicName(onboardingApp.uebTopicName);
1587 app.setUebKey(onboardingApp.getUebKey());
1588 app.setUebSecret(onboardingApp.getUebSecret());
1589 app.setRolesInAAF(onboardingApp.getRolesInAAF());
1590 app.setNameSpace(onboardingApp.getNameSpace());
1591 app.setAppType(new Integer(onboardingApp.getApplicationType()));
1592 app.setModeOfIntegration(onboardingApp.getModeOfIntegration());
1593 app.setAppAck(onboardingApp.getAppAck());
1594 app.setUsesCadi(onboardingApp.getUsesCadi());
1597 if (!StringUtils.isEmpty(onboardingApp.getThumbnail())) {
1598 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1599 String[] splitBase64Thumbnail = onboardingApp.getThumbnail().split("base64,");
1600 logger.debug(EELFLoggerDelegate.debugLogger,
1601 "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1602 if (splitBase64Thumbnail.length > 1) {
1603 // This occurs when we have a new image, not an existing image
1604 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1605 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1606 // This is basically a boolean indicator that an image is
1608 app.setImageUrl(constructImageName(onboardingApp));
1609 app.setThumbnail(decodedImage);
1611 } else if (app.getThumbnail() != null && onboardingApp.getImageLink() == null) {
1612 // The thumbnail that came in from the json is empty; the previous
1613 // thumbnail is NOT empty. Must delete it.
1614 logger.debug(EELFLoggerDelegate.debugLogger,
1615 "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1616 app.setImageUrl(null);
1617 app.setThumbnail(null);
1619 logger.debug(EELFLoggerDelegate.debugLogger,
1620 "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1625 protected String constructImageName(OnboardingApp onboardingApp) {
1626 return "portal_" + String.valueOf(onboardingApp.getLandingPage().hashCode() + "_" + (int) (Math.random() * 100000.0))
1630 // Don't encrypt or decrypt the password if it is null or the empty string
1631 private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1633 if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) {
1635 result = CipherUtil.decryptPKC(encryptedAppPwd,
1636 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1637 } catch (Exception e) {
1638 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1644 protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1646 if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) {
1648 result = CipherUtil.encryptPKC(decryptedAppPwd,
1649 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1650 } catch (Exception e) {
1651 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1657 @SuppressWarnings("unchecked")
1659 public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1660 FieldsValidator fieldsValidator = new FieldsValidator();
1661 final Map<String, Long> params = new HashMap<>();
1662 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1665 params.put("userId", user.getId());
1666 epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1667 Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1668 for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1669 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1671 for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1672 if (epWidgetsManPref.getWidgetid() != null) {
1673 Long widgetid = epWidgetsManPref.getWidgetid();
1674 if (existingWidgetsIds.containsKey(widgetid)) {
1675 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1676 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1677 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1678 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1679 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1680 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1681 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1682 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1684 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1685 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1686 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1687 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1688 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1689 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1690 epWidgetsManualSort.setUserId(user.getId());
1691 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1693 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1696 } catch (Exception e) {
1697 logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1698 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1700 return fieldsValidator;
1703 @SuppressWarnings("unchecked")
1705 public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1706 FieldsValidator fieldsValidator = new FieldsValidator();
1707 final Map<String, Long> params = new HashMap<>();
1708 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1710 params.put("userId", user.getId());
1711 epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1712 Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1713 for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1714 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1716 for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1717 if (delEpWidgetsManPref.getWidgetid() != null) {
1718 Long widgetId = delEpWidgetsManPref.getWidgetid();
1719 if (existingWidgetIds.containsKey(widgetId)) {
1720 params.put("widgetId",widgetId);
1721 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1723 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1726 } catch (Exception e) {
1727 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1728 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1730 return fieldsValidator;
1734 * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1736 * @param: appsSortManual--contains User Apps Data
1738 * @param: user--contains LoggedIn User Data
1740 @SuppressWarnings("unchecked")
1742 public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1743 FieldsValidator fieldsValidator = new FieldsValidator();
1744 final Map<String, Long> params = new HashMap<>();
1745 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1748 params.put("userId", user.getId());
1749 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1750 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1751 for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1752 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1754 for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1755 if (epAppsManPref.getAppid() != null) {
1756 Long appid = epAppsManPref.getAppid();
1757 if (existingAppIds.containsKey(appid)) {
1758 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1760 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1761 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1762 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1763 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1765 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1766 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1768 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1769 epAppsManualSort.setUserId(user.getId());
1770 dataAccessService.saveDomainObject(epAppsManualSort, null);
1772 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1775 } catch (Exception e) {
1776 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1777 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1779 return fieldsValidator;
1785 * @see org.onap.portalapp.portal.service.EPAppService#
1786 * deleteUserAppSortManual(java.lang.String,
1787 * org.onap.portalapp.portal.domain.EPUser)
1789 @SuppressWarnings("unchecked")
1791 public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1792 FieldsValidator fieldsValidator = new FieldsValidator();
1793 final Map<String, Long> params = new HashMap<>();
1794 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1796 params.put("userId", user.getId());
1797 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1798 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1799 for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1800 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1802 if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1803 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1804 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1805 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1807 } catch (Exception e) {
1808 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1809 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1811 return fieldsValidator;
1814 @SuppressWarnings("unchecked")
1816 public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1817 FieldsValidator fieldsValidator = new FieldsValidator();
1818 final Map<String, Long> params = new HashMap<>();
1819 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1820 EPUserAppsSortPreference usrSortPr = null;
1822 params.put("userId", user.getId());
1823 epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1824 if (epSortTypes.size() == 0) {
1825 usrSortPr = new EPUserAppsSortPreference();
1826 usrSortPr.setUserId((int)(long)(user.getId()));
1827 usrSortPr.setSortPref(appsSortPreference.getValue());
1828 dataAccessService.saveDomainObject(usrSortPr, null);
1829 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1831 usrSortPr = epSortTypes.get(0);
1832 usrSortPr.setSortPref(appsSortPreference.getValue());
1833 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1834 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1835 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1836 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1838 } catch (Exception e) {
1839 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1840 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1842 return fieldsValidator;
1845 @SuppressWarnings("unchecked")
1847 public String getUserAppsSortTypePreference(EPUser user) {
1848 final Map<String, Long> params = new HashMap<>();
1849 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1851 params.put("userId", user.getId());
1852 userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1853 if (userSortPrefs.size() > 0)
1854 return userSortPrefs.get(0).getSortPref();
1857 } catch (Exception e) {
1858 logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1865 public List<EPApp> getUserRemoteApps(String id) {
1866 throw new RuntimeException(" Cannot be called from parent class");
1870 public UserRoles getUserProfileForLeftMenu(String loginId) {
1871 final Map<String, String> params = new HashMap<>();
1872 params.put("org_user_id", loginId);
1873 @SuppressWarnings("unchecked")
1874 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1875 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1876 if (usersRolesList == null || usersRolesList.size() < 1)
1879 return usersRolesList.get(0);
1884 public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1885 final Map<String, String> params = new HashMap<>();
1886 params.put("org_user_id", loginId);
1887 @SuppressWarnings("unchecked")
1888 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1889 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1890 if (usersRolesList == null || usersRolesList.size() < 1)
1893 return usersRolesList.get(0);
1897 public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1899 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1900 // If no roles are defined, treat this user as a guest.
1901 if (user.isGuest() || userAndRoles == null) {
1902 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1904 userAndRoles = createUserRoles(user);
1907 return userAndRoles;
1911 public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1913 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1914 // If no roles are defined, treat this user as a guest.
1915 if (user.isGuest() || userAndRoles == null) {
1916 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1918 userAndRoles = createUserRoles(user);
1921 return userAndRoles;
1925 public UserRoles createUserRoles(EPUser user)
1927 UserRole userRole = new UserRole();
1928 userRole.setUser_Id(user.getId());
1929 userRole.setOrgUserId(user.getLoginId());
1930 userRole.setFirstName(user.getFirstName());
1931 userRole.setLastName(user.getLastName());
1932 userRole.setRoleId(-1L);
1933 userRole.setRoleName("Guest");
1934 userRole.setUser_Id(-1L);
1935 UserRoles userAndRoles = new UserRoles(userRole);
1936 return userAndRoles;
1940 @SuppressWarnings("unused")
1942 public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception {
1943 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1944 HttpEntity<String> entity = new HttpEntity<>(headers);
1945 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace);
1946 ResponseEntity<String> response = null;
1949 String namespaceUrl = SystemProperties.
1950 getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "nss/" + namespace;
1952 response = template.exchange(namespaceUrl, HttpMethod.GET, entity, String.class);
1953 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace ,
1954 response.getStatusCode().value());
1955 if (response.getStatusCode().value() == 200) {
1956 String res = response.getBody();
1957 JSONObject jsonObj = new JSONObject(res);
1958 JSONArray namespaceArray = jsonObj.getJSONArray("ns");
1959 if(!namespaceArray.getJSONObject(0).has("admin")){
1960 logger.error(EELFLoggerDelegate.errorLogger,
1961 "No admins are available for requested namespace:" + namespace);
1962 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1963 "Portal Mechid is not an admin of" + namespace);
1966 JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin");
1967 ArrayList<String> list = new ArrayList<String>();
1968 if (namespaceAdminArray != null) {
1969 int len = namespaceAdminArray.length();
1970 for (int i = 0; i < len; i++) {
1971 list.add(namespaceAdminArray.get(i).toString());
1974 logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list);
1975 final String userName = SystemProperties
1976 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
1977 boolean idExists = list.stream().anyMatch(t -> userName.equals(t));
1979 logger.error(EELFLoggerDelegate.errorLogger,
1980 "Portal mechid is not admin of requested namespace:" + namespace);
1981 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1982 "Portal Mechid is not an admin of" + namespace);
1986 } catch (HttpClientErrorException e) {
1987 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
1988 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());