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.MicroserviceData;
79 import org.onap.portalapp.portal.domain.UserRole;
80 import org.onap.portalapp.portal.domain.UserRoles;
81 import org.onap.portalapp.portal.ecomp.model.AppCatalogItem;
82 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
83 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
84 import org.onap.portalapp.portal.transport.EPAppsManualPreference;
85 import org.onap.portalapp.portal.transport.EPAppsSortPreference;
86 import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref;
87 import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
88 import org.onap.portalapp.portal.transport.FieldsValidator;
89 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
90 import org.onap.portalapp.portal.transport.LocalRole;
91 import org.onap.portalapp.portal.transport.OnboardingApp;
92 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
93 import org.onap.portalapp.portal.utils.EcompPortalUtils;
94 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
95 import org.onap.portalsdk.core.onboarding.ueb.Helper;
96 import org.onap.portalsdk.core.onboarding.ueb.TopicManager;
97 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
98 import org.onap.portalsdk.core.onboarding.util.KeyConstants;
99 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
100 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
101 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
102 import org.onap.portalsdk.core.service.DataAccessService;
103 import org.onap.portalsdk.core.util.SystemProperties;
104 import org.springframework.beans.factory.annotation.Autowired;
105 import org.springframework.http.HttpEntity;
106 import org.springframework.http.HttpHeaders;
107 import org.springframework.http.HttpMethod;
108 import org.springframework.http.HttpStatus;
109 import org.springframework.http.ResponseEntity;
110 import org.springframework.web.client.HttpClientErrorException;
111 import org.springframework.web.client.RestTemplate;
113 import com.att.nsa.apiClient.http.HttpException;
114 import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
115 import com.att.nsa.cambria.client.CambriaClientBuilders;
116 import com.att.nsa.cambria.client.CambriaIdentityManager;
117 import com.att.nsa.cambria.client.CambriaTopicManager;
119 public class EPAppCommonServiceImpl implements EPAppService {
121 protected String ECOMP_APP_ID = "1";
122 protected String SUPER_ADMIN_ROLE_ID = "1";
123 protected String ACCOUNT_ADMIN_ROLE_ID = "999";
124 protected String RESTRICTED_APP_ROLE_ID = "900";
126 //private static final String urlField = "url";
127 private static final String nameSpaceField = "url";
129 private static final String nameField = "name";
131 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
134 private AdminRolesService adminRolesService;
136 protected SessionFactory sessionFactory;
138 private DataAccessService dataAccessService;
140 RestTemplate template = new RestTemplate();
143 private void init() {
144 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
145 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
146 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
147 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
150 public Boolean onboardingAppFieldsValidation(OnboardingApp onboardingApp) {
151 //FieldsValidator fieldsValidator = new FieldsValidator();
153 if ((!onboardingApp.getRestrictedApp()) &&( onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0 || onboardingApp.getRestrictedApp() == null
154 || onboardingApp.getLandingPage() == null || onboardingApp.getLandingPage().length() == 0 || onboardingApp.getRestUrl() == null || onboardingApp.getRestUrl().length() == 0
155 || onboardingApp.getAppBasicAuthUsername() == null || onboardingApp.getAppBasicAuthUsername().length() == 0
156 || onboardingApp.getIsOpen() == null
157 || (onboardingApp.getId() != null && onboardingApp.getId().equals(ECOMP_APP_ID)))
158 // For a normal app (appType == PortalConstants.PortalAppId),
159 // these fields must be filled
161 // For a restricted app (appType==2), they will be empty.
162 || ((onboardingApp.getRestrictedApp()) && (onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0
163 || onboardingApp.getLandingPage() == null || onboardingApp.getLandingPage().length() == 0 || onboardingApp.getIsOpen() == null))) {
170 private Boolean onboardingInactiveAppFieldsForValidation(OnboardingApp onboardingApp) {
171 if (onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0
172 || onboardingApp.getIsOpen() == null) {
178 protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
179 FieldsValidator fieldsValidator = new FieldsValidator();
180 if (onboardingApp.getRolesInAAF()) {
181 if (!onboardingApp.getIsEnabled()) {
182 if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
183 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
185 } else if (onboardingApp.getIsEnabled()) {
186 if (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.getNameSpace() == null
187 || onboardingApp.getNameSpace().length() == 0) {
188 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
192 if (!onboardingApp.getIsEnabled()) {
193 if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
194 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
196 } else if (onboardingApp.getIsEnabled()) {
197 if(onboardingApp.getRestrictedApp() && onboardingAppFieldsValidation(onboardingApp) == false){
198 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
200 else if (!onboardingApp.getRestrictedApp() && (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.getAppBasicAuthPassword() == null
201 || onboardingApp.getAppBasicAuthPassword().length() == 0)) {
202 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
206 return fieldsValidator;
210 public List<EPApp> getUserAsAdminApps(EPUser user) {
211 if (adminRolesService.isAccountAdmin(user)) {
212 String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
213 + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
214 + " AND FN_APP.ENABLED = 'Y'";
217 @SuppressWarnings("unchecked")
218 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
220 } catch (Exception e) {
221 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
226 logger.error(EELFLoggerDelegate.errorLogger,
227 "getUserAsAdminApps: only Account Admin may invoke this function!");
228 return new ArrayList<EPApp>();
235 public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
236 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
237 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
238 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
239 + " AND FN_APP.ENABLED = 'Y'";
241 String sql = String.format(format, orgUserId);
245 @SuppressWarnings("unchecked")
246 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
248 } catch (Exception e) {
249 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
255 public List<EPApp> getAppsFullList() {
256 @SuppressWarnings("unchecked")
257 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
262 public List<EcompApp> getEcompAppAppsFullList() {
263 return transformAppsToEcompApps(getAppsFullList());
267 public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
268 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
269 for (EPApp app : appsList) {
270 EcompApp ecompApp = new EcompApp();
271 ecompApp.setId(app.getId());
272 ecompApp.setName(app.getName());
273 ecompApp.setImageUrl(app.getImageUrl());
274 ecompApp.setDescription(app.getAppDescription());
275 ecompApp.setNotes(app.getAppNotes());
276 ecompApp.setUrl(app.getLandingPage());
277 ecompApp.setAlternateUrl(app.getAlternateLandingPage());
278 ecompApp.setUebTopicName(app.getUebTopicName());
279 //ecompApp.setUebKey(app.getUebKey());
280 ecompApp.setUebSecret(app.getUebSecret());
281 ecompApp.setEnabled(app.getEnabled());
282 ecompApp.setCentralAuth(app.getRolesInAAF());
283 ecompApp.setNameSpace(app.getNameSpace());
284 ecompApp.setRestrictedApp(app.isRestrictedApp());
285 ecompAppList.add(ecompApp);
291 public EPApp getApp(Long appId) {
293 return (EPApp) dataAccessService.getDomainObject(EPApp.class, appId, null);
294 } catch (Exception e) {
295 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
302 @SuppressWarnings("unchecked")
304 public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
306 if (adminRolesService.isAccountAdmin(user) && adminRolesService.isRoleAdmin(user)) {
307 final Map<String, Long> params = new HashMap<>();
308 params.put("userId", user.getId());
309 List applicationRoleswithAccountandRoleadmin = dataAccessService
310 .executeNamedQuery("getApplicationsofTheUserwithAdminAndRoleAdmin", params, null);
312 return applicationRoleswithAccountandRoleadmin;
313 } catch (Exception e) {
314 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
315 logger.error(EELFLoggerDelegate.errorLogger,
316 "Exception occurred while fetching the list of user who has type account and role approver "
323 if (adminRolesService.isAccountAdmin(user)) {
324 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 "
325 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
326 + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
327 String sql = String.format(format, user.getId());
330 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
331 } catch (Exception e) {
332 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
333 logger.error(EELFLoggerDelegate.errorLogger,
334 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
339 if (adminRolesService.isRoleAdmin(user)) {
340 final Map<String, Long> params = new HashMap<>();
341 params.put("userId", user.getId());
342 List applicationRoles = dataAccessService.executeNamedQuery("getApplicationsofTheUserContainsApprover",
346 return applicationRoles;
347 } catch (Exception e) {
348 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
349 logger.error(EELFLoggerDelegate.errorLogger,
350 "Exception occurred while fetching the list of user who has type approver "
357 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
358 // app.APP_REST_ENDPOINT <> ''";
360 return new ArrayList<AppIdAndNameTransportModel>();
364 public EPApp getAppDetail(String appName) {
365 final Map<String, String> params = new HashMap<String, String>();
367 params.put("appName", appName);
368 @SuppressWarnings("unchecked")
369 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
370 return (apps.size() > 0) ? apps.get(0) : null;
371 } catch(Exception e) {
372 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
378 public EPApp getAppDetailByAppName(String appName) {
379 final Map<String, String> params = new HashMap<String, String>();
381 params.put("appName", appName);
382 @SuppressWarnings("unchecked")
383 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getAppDetailsByAppName", params, null);
384 if (apps.size() > 0) {
385 EPApp app = apps.get(0);
386 if (!EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
387 app.setRolesInAAF(false);
393 } catch (Exception e) {
394 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
399 @SuppressWarnings("unchecked")
401 public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
402 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
405 if (adminRolesService.isSuperAdmin(user)) {
406 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
407 + "where app.ENABLED = 'Y' AND app.app_type = 1";
409 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 "
410 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
411 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
413 sql = String.format(format, user.getId());
414 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
415 // app.APP_REST_ENDPOINT <> ''";
418 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
419 } catch (Exception e) {
420 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
421 logger.error(EELFLoggerDelegate.errorLogger,
422 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
425 return new ArrayList<AppIdAndNameTransportModel>();
428 protected void logQuery(String sql) {
429 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
432 public DataAccessService getDataAccessService() {
433 return dataAccessService;
436 public void setDataAccessService(DataAccessService dataAccessService) {
437 this.dataAccessService = dataAccessService;
440 @SuppressWarnings("unchecked")
442 public List<AdminUserApplications> getAppsAdmins() {
444 Map<String, String> params = new HashMap<>();
445 params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
446 List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
448 return aggregateRowsResultsByUserId(adminApps);
449 } catch (Exception e) {
450 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
455 private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
456 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
457 for (AdminUserApp app : adminApps) {
458 Long userId = app.getUser_Id();
459 if (adminUserApplications.get(userId) == null)
460 adminUserApplications.put(userId, new AdminUserApplications(app));
462 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
464 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
468 public List<AppsResponse> getAllApps(Boolean all) {
469 // If all is true, return both active and inactive apps. Otherwise, just
471 @SuppressWarnings("unchecked")
472 // Sort the list by application name so the drop-down looks pretty.
473 List<EPApp> apps = all
474 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
475 : (List<EPApp>) dataAccessService.getList(EPApp.class,
476 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
478 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
479 for (EPApp app : apps) {
480 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
487 public List<AppsResponse> getAllApplications(Boolean all) {
488 // If all is true, return both active and inactive apps. Otherwise, just
490 @SuppressWarnings("unchecked")
491 // Sort the list by application name so the drop-down looks pretty.
492 List<EPApp> apps = all
493 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
494 :dataAccessService.getList(EPApp.class, null);
496 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
497 for (EPApp app : apps) {
498 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
503 public UserRoles getUserProfile(String loginId) {
504 final Map<String, String> params = new HashMap<>();
505 params.put("org_user_id", loginId);
506 @SuppressWarnings("unchecked")
507 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
508 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
509 if (usersRolesList == null || usersRolesList.size() < 1)
512 return usersRolesList.get(0);
516 public UserRoles getUserProfileNormalized(EPUser user) {
518 UserRoles userAndRoles = getUserProfile(user.getLoginId());
519 // If no roles are defined, treat this user as a guest.
520 if (user.isGuest() || userAndRoles == null) {
521 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
523 UserRole userRole = new UserRole();
524 userRole.setUser_Id(user.getId());
525 userRole.setOrgUserId(user.getLoginId());
526 userRole.setFirstName(user.getFirstName());
527 userRole.setLastName(user.getLastName());
528 userRole.setRoleId(-1L);
529 userRole.setRoleName("Guest");
530 userRole.setUser_Id(-1L);
531 userAndRoles = new UserRoles(userRole);
537 protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
538 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
539 for (UserRole user : userRoleList) {
540 String orgUserId = user.getOrgUserId();
541 if (userRoles.get(orgUserId) == null)
542 userRoles.put(orgUserId, new UserRoles(user));
544 userRoles.get(orgUserId).addRole(user.getRoleName());
546 return new ArrayList<UserRoles>(userRoles.values());
549 private boolean isRestrictedApp(Long appId) {
550 EPApp app = getApp(appId);
551 return app.isRestrictedApp();
554 // For the functional menu edit
556 public List<LocalRole> getAppRoles(Long appId) {
558 if (isRestrictedApp(appId)) {
559 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
560 }else if(appId == 1){
561 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
563 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
566 @SuppressWarnings("unchecked")
567 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
571 protected String userAppsQuery(EPUser user) {
572 StringBuilder query = new StringBuilder();
573 if (adminRolesService.isSuperAdmin(user)) {
574 query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
576 query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
578 "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
579 query.append(" AND FN_APP.ENABLED = 'Y'");
581 return query.toString();
584 /*protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
585 FieldsValidator fieldsValidator = new FieldsValidator();
586 if(onboardingApp.isCentralAuth){
587 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
588 || onboardingApp.url.length() == 0 || onboardingApp.getRestrictedApp() == null
589 || onboardingApp.getIsOpen() == null || onboardingApp.getIsEnabled() == null
590 || (onboardingApp.getId() != null && ECOMP_APP_ID.equals(onboardingApp.getId().toString()))
591 // For a normal app (appType == PortalConstants.PortalAppId),
592 // these fields must be filled
594 // For a restricted app (appType==2), they will be empty.
595 || ((!onboardingApp.getRestrictedApp()) && (onboardingApp.myLoginsAppName == null
596 || onboardingApp.myLoginsAppName.length() == 0 || onboardingApp.myLoginsAppOwner == null
597 || onboardingApp.myLoginsAppOwner.length() == 0 || onboardingApp.username == null
598 || onboardingApp.username.length() == 0 ))) {
599 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
603 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
604 || onboardingApp.url.length() == 0 || onboardingApp.getRestrictedApp() == null
605 || onboardingApp.getIsOpen() == null || onboardingApp.getIsEnabled() == null
606 || (onboardingApp.getId() != null && ECOMP_APP_ID.equals(onboardingApp.getId().toString()))
607 // For a normal app (appType == PortalConstants.PortalAppId),
608 // these fields must be filled
610 // For a restricted app (appType==2), they will be empty.
611 || ((!onboardingApp.getRestrictedApp()) && (onboardingApp.myLoginsAppName == null
612 || onboardingApp.myLoginsAppName.length() == 0 || onboardingApp.myLoginsAppOwner == null
613 || onboardingApp.myLoginsAppOwner.length() == 0 || onboardingApp.username == null
614 || onboardingApp.username.length() == 0 || onboardingApp.appPassword == null
615 || onboardingApp.appPassword.length() == 0))) {
616 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
621 return fieldsValidator;
625 public List<EPApp> getUserApps(EPUser user) {
626 List<EPApp> openApps = getOpenApps();
628 if (user.isGuest()) {
631 String sql = userAppsQuery(user);
634 // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
635 List<EPApp> appsList = new ArrayList<>();
636 @SuppressWarnings("unchecked")
637 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
638 HashSet<EPApp> appSet = new HashSet<>();
639 for (EPApp app : adminApps) {
644 for (EPApp app : openApps) {
645 if (!appSet.contains(app))
654 public List<EPApp> getPersAdminApps(EPUser user) {
655 final Map<String, Long> params = new HashMap<>();
656 params.put("userId", user.getId());
657 // Named query is stored in EP.hbm.xml, mapped to EPApp
658 @SuppressWarnings("unchecked")
659 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
664 public List<EPApp> getPersUserApps(EPUser user) {
665 final Map<String, Long> params = new HashMap<>();
666 params.put("userId", user.getId());
667 // Named query is stored in EP.hbm.xml, mapped to EPApp
668 @SuppressWarnings("unchecked")
669 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
677 * org.onap.portalapp.portal.service.EPAppService#getAppCatalog(
678 * org.onap.portalapp.portal.domain.EPUser)
681 public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
682 final Map<String, Long> params = new HashMap<>();
683 params.put("userId", user.getId());
684 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
685 @SuppressWarnings("unchecked")
686 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
694 * org.onap.portalapp.portal.service.EPAppService#getAdminAppCatalog(
695 * org.onap.portalapp.portal.domain.EPUser)
698 public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
699 final Map<String, Long> params = new HashMap<>();
700 params.put("userId", user.getId());
701 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
702 @SuppressWarnings("unchecked")
703 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
707 private List<EPApp> getOpenApps() {
708 @SuppressWarnings("unchecked")
709 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
713 @SuppressWarnings("unchecked")
715 public List<EPApp> getAppsOrderByName(EPUser user) {
716 final Map<String, Long> params = new HashMap<>();
717 List<EPApp> sortedAppsByName = null;
719 if (adminRolesService.isSuperAdmin(user)) {
720 params.put("userId", user.getId());
721 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
723 params.put("userId", user.getId());
724 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
726 } catch (Exception e) {
727 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
729 return sortedAppsByName;
732 @SuppressWarnings("unchecked")
734 public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
736 final Map<String, Long> params = new HashMap<>();
737 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
738 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
740 if (adminRolesService.isSuperAdmin(user)) {
741 params.put("userId", user.getId());
742 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
744 params.put("userId", user.getId());
745 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
747 Set<String> epAppSet = new HashSet<String>();
748 for (EPApp eapp : sortedAppsByLastUsed)
749 if (!epAppSet.contains(eapp.getName())) {
750 finalsortedAppsByLastUsed.add(eapp);
751 epAppSet.add(eapp.getName());
754 } catch (Exception e) {
755 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
757 return finalsortedAppsByLastUsed;
760 @SuppressWarnings("unchecked")
762 public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
763 final Map<String, Long> params = new HashMap<>();
764 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
765 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
767 if (adminRolesService.isSuperAdmin(user)) {
768 params.put("userId", user.getId());
769 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
771 params.put("userId", user.getId());
772 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
774 Set<String> epAppSet = new HashSet<String>();
776 for (EPApp eapp : sortedAppsByMostUsed) {
777 if (!epAppSet.contains(eapp.getName())) {
778 finalsortedAppsByMostUsed.add(eapp);
779 epAppSet.add(eapp.getName());
782 } catch (Exception e) {
783 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
786 return finalsortedAppsByMostUsed;
790 * This Method retrieves the User Apps by Sort Manual Preference
792 * @param: user--contains LoggedIn User Data
794 @SuppressWarnings("unchecked")
796 public List<EPApp> getAppsOrderByManual(EPUser user) {
797 final Map<String, Long> params = new HashMap<>();
798 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
799 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
801 if (adminRolesService.isSuperAdmin(user)) {
802 params.put("userId", user.getId());
803 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
805 params.put("userId", user.getId());
806 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
808 Set<String> epAppSet = new HashSet<String>();
810 for (EPApp eapp : sortedAppsByManual) {
811 if (!epAppSet.contains(eapp.getName())) {
812 finalsortedAppsByManual.add(eapp);
813 epAppSet.add(eapp.getName());
816 } catch (Exception e) {
817 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
819 return finalsortedAppsByManual;
823 public List<OnboardingApp> getOnboardingApps() {
824 @SuppressWarnings("unchecked")
825 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
826 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
827 for (EPApp app : apps) {
828 OnboardingApp onboardingApp = new OnboardingApp();
829 app.setAppBasicAuthPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);//to hide password from get request
830 createOnboardingFromApp(app, onboardingApp);
831 onboardingAppsList.add(onboardingApp);
833 return onboardingAppsList;
836 @SuppressWarnings("unchecked")
838 public List<OnboardingApp> getAdminAppsOfUser(EPUser user) {
840 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
841 List<Integer> userAdminApps = new ArrayList<>();
842 final Map<String, Long> userParams = new HashMap<>();
843 userParams.put("userId", user.getId());
844 userAdminApps = dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
846 // userAdminApps.removeIf(x -> x == Integer.valueOf(ECOMP_APP_ID));
848 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size());
849 onboardingAppsList = getOnboardingApps();
851 final List<Integer> userAdminApps1 = userAdminApps;
852 List<OnboardingApp> userApplicationAdmins = onboardingAppsList.stream().filter(x -> userAdminApps1.contains((int) (long)x.getId())).collect(Collectors.toList());
854 return userApplicationAdmins;
858 public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
859 @SuppressWarnings("unchecked")
860 List<EPApp> apps = dataAccessService.getList(EPApp.class,
861 " where enabled = true and open = false and app_type!= 3 and id!=" + ECOMP_APP_ID, null, null);
863 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
864 for (EPApp app : apps) {
865 OnboardingApp onboardingApp = new OnboardingApp();
866 createOnboardingFromApp(app, onboardingApp);
867 onboardingAppsList.add(onboardingApp);
869 return onboardingAppsList;
872 @SuppressWarnings("unchecked")
873 private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
874 boolean duplicatedNameSpace = false;
875 boolean duplicatedName = false;
877 if (onboardingApp.getId() == null) {
878 List<Criterion> restrictionsList = new ArrayList<Criterion>();
879 Criterion nameCrit = Restrictions.eq("name",onboardingApp.getAppName());
880 Criterion nameSpaceCrit = null;
881 Criterion orCrit = null;
882 if (onboardingApp.getRolesInAAF()) {
883 nameSpaceCrit = Restrictions.eq("nameSpace", onboardingApp.getNameSpace());
884 orCrit = Restrictions.or(nameCrit, nameSpaceCrit);
886 orCrit = Restrictions.or(nameCrit);
887 restrictionsList.add(orCrit);
888 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
890 List<Criterion> restrictionsList = new ArrayList<Criterion>();
891 Criterion idCrit =Restrictions.eq("id", onboardingApp.getId());
892 Criterion nameCrit = Restrictions.eq("name",onboardingApp.getAppName());
893 Criterion nameSpaceCrit = null;
894 Criterion orCrit= null;
895 if (onboardingApp.getRolesInAAF()) {
896 nameSpaceCrit = Restrictions.eq("nameSpace",onboardingApp.getNameSpace());
897 orCrit = Restrictions.or(idCrit, nameSpaceCrit, nameCrit);
900 orCrit = Restrictions.or(idCrit, nameCrit);
902 restrictionsList.add(orCrit);
903 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
906 for (EPApp app : apps) {
907 if (onboardingApp.getId() != null && onboardingApp.getId().equals(app.getId())) {
910 if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.getAppName())) {
911 duplicatedName = true;
912 if (duplicatedName) {
916 if (!duplicatedNameSpace && app.getNameSpace().equalsIgnoreCase(onboardingApp.getNameSpace())) {
917 duplicatedNameSpace = true;
918 if (duplicatedNameSpace) {
924 if (duplicatedNameSpace || duplicatedName) {
925 if (duplicatedNameSpace) {
926 fieldsValidator.addProblematicFieldName(nameSpaceField);
928 if (duplicatedName) {
929 fieldsValidator.addProblematicFieldName(nameField);
931 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
932 fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
937 public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
938 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
939 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
940 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
941 validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
943 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
944 if (modifiedOnboardingApp.getId() != null) {
945 updateApp(modifiedOnboardingApp.getId(), modifiedOnboardingApp, fieldsValidator, user);
946 logger.info(EELFLoggerDelegate.auditLogger, "Updated " + modifiedOnboardingApp.getAppName() +
947 " onboarding application details by user " + user.getLoginId());
949 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
952 return fieldsValidator;
956 public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
957 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
958 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
959 validateOnboardingApp(newOnboardingApp, fieldsValidator);
961 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
962 if (newOnboardingApp.getId() == null) {
963 updateApp(null, newOnboardingApp, fieldsValidator, user);
964 logger.info(EELFLoggerDelegate.auditLogger, "Added " + newOnboardingApp.getAppName() +
965 " Onboarding application by user " + user.getLoginId());
967 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
970 return fieldsValidator;
973 @SuppressWarnings("unchecked")
975 public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
976 FieldsValidator fieldsValidator = new FieldsValidator();
977 if (!adminRolesService.isSuperAdmin(user)) {
978 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
979 return fieldsValidator;
981 final Map<String, Long> params = new HashMap<>();
982 params.put("app_id", appid);
984 //Checking if App is associated with any exiting microservices- ep_microservice:
985 final Map<String, Long> queryparams = new HashMap<>();
986 queryparams.put("applicationId", appid);
987 List<MicroserviceData> microservicesList = dataAccessService.executeNamedQuery( "getMicroservicesByAppId", queryparams, null);
988 if(microservicesList!=null && microservicesList.size()>0) {
989 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
990 return fieldsValidator;
993 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
994 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
995 for(int i=0;i<EPUserAppRolesRequestList.size();i++)
997 dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
1000 Session localSession = null;
1001 Transaction transaction = null;
1002 Boolean result = false;
1004 localSession = sessionFactory.openSession();
1005 transaction = localSession.beginTransaction();
1007 // 1) Remove the URL for any functional menu item associated with
1009 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
1010 // Named query is stored in EP.hbm.xml, mapped to EPApp
1011 dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
1012 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted URL for any functional menu item associated with app");
1014 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
1015 // 2)Remove any favorites associated with a menu item that is
1016 // associated with this app
1017 dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
1018 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
1020 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
1021 // 3)Remove all role, appid records from fn_menu_functional_role
1022 // that are associated with this app
1023 dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
1024 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
1026 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1027 // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
1028 // that are associated with this app
1029 dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
1030 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1032 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
1033 // 5)Remove all rolefunctions, appid records from ep_app_function
1034 // that are associated with this app
1035 dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
1036 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
1038 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
1039 // 6)Remove all records from fn_user_role associated with this app
1040 dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
1041 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
1043 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
1044 // 7)Remove any widgets associated with this app
1045 dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
1046 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
1048 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
1049 // 8)Remove any roles associated with this app
1050 dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
1051 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
1053 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
1054 // 9)Remove all records from fn_role associated with this app
1055 dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
1056 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
1058 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
1059 // 10)Remove app contact us entries
1060 dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
1061 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
1063 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
1064 // 11)Remove rows in the app personalization selection table
1065 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
1066 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
1068 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
1069 // 12)Remove rows in the app personalization sort table
1070 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
1071 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
1073 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
1074 // 13)Remove rows in the app personalization sort table
1075 dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
1076 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
1078 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
1079 // 14)Remove rows in the ep_web_analytics_source
1080 dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
1081 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
1083 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
1084 // 15)Delete the app
1085 dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
1086 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
1089 // 1) Remove the URL for any functional menu item associated with
1091 String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
1092 + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
1094 Query query = localSession.createSQLQuery(sql);
1095 query.executeUpdate();
1097 // Remove any favorites associated with a menu item that is
1098 // associated with this app
1099 sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
1100 + " where fn_menu_functional_roles.app_id='" + appid + "' "
1101 + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
1103 query = localSession.createSQLQuery(sql);
1104 query.executeUpdate();
1106 // Remove all role, appid records from fn_menu_functional_role
1107 // that are associated with this app
1108 sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
1110 query = localSession.createSQLQuery(sql);
1111 query.executeUpdate();
1114 // Remove all roles, rolefunctions, appid records from ep_app_role_function
1115 // that are associated with this app
1116 sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
1117 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1118 query = localSession.createSQLQuery(sql);
1119 query.executeUpdate();
1121 //Remove all rolefunctions, appid records from ep_app_function
1122 // that are associated with this app
1123 sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
1124 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1125 query = localSession.createSQLQuery(sql);
1126 query.executeUpdate();
1128 // Remove all records from fn_user_role associated with this app
1129 sql = "delete from fn_user_role where app_id='" + appid + "'";
1131 query = localSession.createSQLQuery(sql);
1132 query.executeUpdate();
1134 // Remove any widgets associated with this app
1135 sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
1137 query = localSession.createSQLQuery(sql);
1138 query.executeUpdate();
1140 // Remove any roles associated with this app
1141 sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
1142 + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
1144 query = localSession.createSQLQuery(sql);
1145 query.executeUpdate();
1147 // Remove all records from fn_role associated with this app
1148 sql = "delete from fn_role where app_id='" + appid + "'";
1150 query = localSession.createSQLQuery(sql);
1151 query.executeUpdate();
1153 // Remove app contact us entries
1154 sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
1156 query = localSession.createSQLQuery(sql);
1157 query.executeUpdate();
1159 // Remove rows in the app personalization selection table
1160 sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
1162 query = localSession.createSQLQuery(sql);
1163 query.executeUpdate();
1165 // Remove rows in the app personalization sort table
1166 sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
1168 query = localSession.createSQLQuery(sql);
1169 query.executeUpdate();
1171 // Remove rows in the app personalization sort table
1172 sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
1174 query = localSession.createSQLQuery(sql);
1175 query.executeUpdate();
1177 // Remove rows in the app personalization sort table
1178 sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
1180 query = localSession.createSQLQuery(sql);
1181 query.executeUpdate();
1184 sql = "delete from fn_app where app_id='" + appid + "'";
1186 query = localSession.createSQLQuery(sql);
1187 query.executeUpdate();
1189 transaction.commit();
1192 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
1193 } catch (Exception e) {
1194 logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
1195 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
1196 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
1198 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
1201 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1203 return fieldsValidator;
1206 private static Object syncRests = new Object();
1208 // An app has been enabled/disabled. Must enable/disable all associated
1209 // functional menu items.
1210 protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1211 String active_yn = enabled ? "Y" : "N";
1212 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1213 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1214 + " AND r.app_id = '" + appId + "' ";
1216 @SuppressWarnings("unchecked")
1217 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1218 for (FunctionalMenuItem menuItem : menuItems) {
1219 FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1221 myMenuItem.active_yn = active_yn;
1222 localSession.save(myMenuItem);
1226 // Attention! If (appId == null) we use this function to create application
1227 // otherwise we use it to modify existing application
1228 protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1229 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1230 // Separate out the code for a restricted app, since it doesn't need any
1232 if (Boolean.TRUE.equals(onboardingApp.getRestrictedApp())) {
1233 boolean result = false;
1234 Session localSession = null;
1235 Transaction transaction = null;
1237 localSession = sessionFactory.openSession();
1238 transaction = localSession.beginTransaction();
1240 if (appId == null) {
1243 app = (EPApp) localSession.get(EPApp.class, appId);
1244 if (app == null || app.getId() == null) { // App is already
1246 transaction.commit();
1247 localSession.close();
1248 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1252 createAppFromOnboarding(app, onboardingApp, localSession);
1253 localSession.saveOrUpdate(app);
1254 // Enable or disable all menu items associated with this app
1255 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1256 transaction.commit();
1258 } catch (Exception e) {
1259 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1260 EcompPortalUtils.rollbackTransaction(transaction,
1261 "updateApp rollback, exception = " + e.toString());
1263 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1266 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1270 updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1276 protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1278 synchronized (syncRests) {
1279 boolean result = false;
1280 Session localSession = null;
1281 Transaction transaction = null;
1283 localSession = sessionFactory.openSession();
1284 transaction = localSession.beginTransaction();
1286 if (appId == null) {
1289 * In the parent class, the UEB code is responsible for generating the
1290 * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1291 * may be used in future at which point we can just remove this method and
1292 * depend on parent class's method So, using UUID generator to generate the
1293 * unique key instead.
1295 String uuidStr = UUID.randomUUID().toString();
1296 String appKey = uuidStr;
1297 String appSecret = uuidStr;
1298 String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1299 onboardingApp.setUebTopicName(appMailboxName);
1300 onboardingApp.setUebKey(appKey);
1301 onboardingApp.setUebSecret(appSecret);
1303 app = (EPApp) localSession.get(EPApp.class, appId);
1304 if (app == null || app.getId() == null) {
1305 // App is already deleted!
1306 transaction.commit();
1307 localSession.close();
1308 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1312 logger.debug(EELFLoggerDelegate.debugLogger,
1313 "updateRestrictedApp: about to call createAppFromOnboarding");
1314 createAppFromOnboarding(app, onboardingApp, localSession);
1315 logger.debug(EELFLoggerDelegate.debugLogger,
1316 "updateRestrictedApp: finished calling createAppFromOnboarding");
1317 localSession.saveOrUpdate(app);
1318 logger.debug(EELFLoggerDelegate.debugLogger,
1319 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1320 // Enable or disable all menu items associated with this app
1321 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1322 logger.debug(EELFLoggerDelegate.debugLogger,
1323 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1324 transaction.commit();
1325 logger.debug(EELFLoggerDelegate.debugLogger,
1326 "updateRestrictedApp: finished calling transaction.commit");
1328 } catch (Exception e) {
1329 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1330 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1331 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1332 EcompPortalUtils.rollbackTransaction(transaction,
1333 "updateRestrictedApp rollback, exception = " + e.toString());
1335 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1338 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1345 protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1347 synchronized (syncRests) {
1348 boolean result = false;
1349 Session localSession = null;
1350 Transaction transaction = null;
1352 localSession = sessionFactory.openSession();
1353 transaction = localSession.beginTransaction();
1355 if (appId == null) {
1357 // -------------------------------------------------------------------------------------------
1358 // Register this App with the UEB communication server.
1360 // the App's unique mailbox/topic
1361 // name and keys to the FN_APP table. The App's mailbox
1363 // keys will be visible to the
1364 // admin on the ONAP portal.
1365 // -------------------------------------------------------------------------------------------
1366 TopicManager topicManager = new TopicManager() {
1368 EPAppCommonServiceImpl service;
1370 public void init(EPAppCommonServiceImpl _service) {
1374 public void createTopic(String key, String secret, String topicName,
1375 String topicDescription) throws HttpException, CambriaApiException, IOException {
1377 init(EPAppCommonServiceImpl.this);
1378 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1379 if (logger.isInfoEnabled()) {
1380 logger.info("==> createTopic");
1381 logger.info("topicName: " + topicName);
1382 logger.info("topicDescription: " + topicDescription);
1384 CambriaTopicManager tm = null;
1386 tm = service.getTopicManager(urlList, key, secret);
1387 } catch (Exception e) {
1388 logger.error("pub.build Exception ", e);
1389 throw new CambriaApiException(topicName);
1391 tm.createTopic(topicName, topicDescription, 1, 1);
1394 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1395 String topicName) throws HttpException, CambriaApiException, IOException {
1396 logger.info("==> addPublisher to topic " + topicName);
1397 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1398 CambriaTopicManager tm = null;
1400 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1401 } catch (Exception e) {
1402 logger.error("pub.build Exception ", e);
1403 throw new CambriaApiException(topicName);
1405 tm.allowProducer(topicName, publisherKey);
1409 final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1410 .usingHosts(Helper.uebUrlList()).build();
1411 com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1412 "ONAP Portal Owner");
1413 String appKey = credential.getApiKey();
1414 String appSecret = credential.getApiSecret();
1415 String appMailboxName = null;
1417 int maxNumAttemptsToCreateATopic = 3;
1418 boolean successfullyCreatedMailbox = false;
1419 for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1420 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1423 topicManager.createTopic(
1424 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1425 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1426 appMailboxName, "ECOMP outbox for app" + onboardingApp.getAppName());
1427 successfullyCreatedMailbox = true;
1428 logger.debug(EELFLoggerDelegate.debugLogger,
1429 "Successfully created " + appMailboxName + " for App " + onboardingApp.getAppName());
1430 logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
1431 + appSecret + " generated using = " + user.getEmail());
1433 } catch (HttpException e) {
1434 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1435 if (e.getStatusCode() == 409) {
1436 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1437 + " already exists. Will try using a different name", e);
1439 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1445 if (successfullyCreatedMailbox) {
1446 onboardingApp.setUebTopicName(appMailboxName);
1447 onboardingApp.setUebKey(appKey);
1448 onboardingApp.setUebSecret(appSecret);
1452 * EP is a publisher to this App's new mailbox
1454 topicManager.addPublisher(
1455 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1456 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1457 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1461 * This App is a subscriber of its own mailbox
1463 topicManager.addSubscriber(
1464 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1465 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1469 * This App is a publisher to EP
1471 topicManager.addPublisher(
1472 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1473 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1474 PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1475 } catch (HttpException | CambriaApiException | IOException e) {
1476 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1477 logger.error(EELFLoggerDelegate.errorLogger,
1478 "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1479 transaction.commit();
1480 localSession.close();
1481 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1485 transaction.commit();
1486 localSession.close();
1487 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1491 app = (EPApp) localSession.get(EPApp.class, appId);
1492 if (app == null || app.getId() == null) {
1493 // App is already deleted!
1494 transaction.commit();
1495 localSession.close();
1496 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1500 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1501 createAppFromOnboarding(app, onboardingApp, localSession);
1502 logger.debug(EELFLoggerDelegate.debugLogger,
1503 "LR: updateApp: finished calling createAppFromOnboarding");
1504 localSession.saveOrUpdate(app);
1505 logger.debug(EELFLoggerDelegate.debugLogger,
1506 "LR: updateApp: finished calling localSession.saveOrUpdate");
1507 // Enable or disable all menu items associated with this app
1508 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1509 logger.debug(EELFLoggerDelegate.debugLogger,
1510 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1511 transaction.commit();
1512 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1513 logger.debug(EELFLoggerDelegate.debugLogger,
1514 "LR: updateApp: finished calling epUebHelper.addPublisher");
1516 } catch (Exception e) {
1517 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1518 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1519 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1520 EcompPortalUtils.rollbackTransaction(transaction,
1521 "updateApp rollback, exception = " + e.toString());
1523 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1526 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1532 public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1533 throws GeneralSecurityException, Exception {
1534 throw new Exception("This method can only be invoked from child class");
1538 * Populates a transport model of the application from a database row model.
1539 * Leaves out the thumbnail because the FE fetches images via a different
1543 * Model of database row
1544 * @param onboardingApp
1545 * Model for transport as JSON
1548 public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1549 onboardingApp.setId(app.getId());
1550 onboardingApp.setAppName(app.getName());
1551 onboardingApp.setImageUrl(app.getImageUrl());
1552 onboardingApp.setAppDescription(app.getAppDescription());
1553 onboardingApp.setAppNotes(app.getAppNotes());
1554 onboardingApp.setLandingPage(app.getLandingPage());
1555 onboardingApp.setAlternateLandingPage(app.getAlternateLandingPage());
1556 onboardingApp.setRestUrl(app.getAppRestEndpoint());
1557 onboardingApp.setIsOpen(app.getOpen());
1558 onboardingApp.setIsEnabled(app.getEnabled());
1559 onboardingApp.setAppBasicAuthUsername(app.getAppBasicAuthUsername());
1561 String effectivePwd = null;
1562 if (app.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1563 effectivePwd = EPCommonSystemProperties.APP_DISPLAY_PASSWORD;
1565 effectivePwd = decryptedPassword(app.getAppBasicAuthPassword(), app);
1567 onboardingApp.setAppBasicAuthPassword(effectivePwd);
1568 onboardingApp.setUebTopicName(app.getUebTopicName());
1569 onboardingApp.setUebKey(app.getUebKey());
1570 onboardingApp.setUebSecret(app.getUebSecret());
1571 onboardingApp.setRolesInAAF(app.getRolesInAAF());
1572 onboardingApp.setNameSpace(app.getNameSpace());
1573 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1574 onboardingApp.setModeOfIntegration(app.getModeOfIntegration());
1575 onboardingApp.setAppAck(app.getAppAck());
1576 onboardingApp.setUsesCadi(app.getUsesCadi());
1577 onboardingApp.setApplicationType(app.getAppType().toString());
1581 * Creates a database object for an application from an uploaded transport
1582 * model. Must decode the thumbnail, if any.
1585 * @param onboardingApp
1586 * @param localSession
1587 * @return The first argument.
1589 protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1590 app.setName(onboardingApp.getAppName());
1591 app.setAppDescription(onboardingApp.getAppDescription());
1592 app.setAppNotes(onboardingApp.getAppNotes());
1593 app.setLandingPage(onboardingApp.getLandingPage());
1594 app.setAlternateLandingPage(onboardingApp.getAlternateLandingPage());
1595 app.setAppRestEndpoint(onboardingApp.getRestUrl());
1596 app.setOpen(onboardingApp.getIsOpen());
1597 app.setEnabled(onboardingApp.getIsEnabled());
1598 app.setAppBasicAuthUsername(onboardingApp.getAppBasicAuthUsername());
1599 if(!onboardingApp.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1600 app.setAppBasicAuthPassword(this.encryptedPassword(onboardingApp.getAppBasicAuthPassword(), app));
1601 //app.setUebTopicName(onboardingApp.uebTopicName);
1602 app.setUebKey(onboardingApp.getUebKey());
1603 app.setUebSecret(onboardingApp.getUebSecret());
1604 app.setRolesInAAF(onboardingApp.getRolesInAAF());
1605 app.setNameSpace(onboardingApp.getNameSpace());
1606 app.setAppType(new Integer(onboardingApp.getApplicationType()));
1607 app.setModeOfIntegration(onboardingApp.getModeOfIntegration());
1608 app.setAppAck(onboardingApp.getAppAck());
1609 app.setUsesCadi(onboardingApp.getUsesCadi());
1612 if (!StringUtils.isEmpty(onboardingApp.getThumbnail())) {
1613 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1614 String[] splitBase64Thumbnail = onboardingApp.getThumbnail().split("base64,");
1615 logger.debug(EELFLoggerDelegate.debugLogger,
1616 "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1617 if (splitBase64Thumbnail.length > 1) {
1618 // This occurs when we have a new image, not an existing image
1619 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1620 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1621 // This is basically a boolean indicator that an image is
1623 app.setImageUrl(constructImageName(onboardingApp));
1624 app.setThumbnail(decodedImage);
1626 } else if (app.getThumbnail() != null && onboardingApp.getImageLink() == null) {
1627 // The thumbnail that came in from the json is empty; the previous
1628 // thumbnail is NOT empty. Must delete it.
1629 logger.debug(EELFLoggerDelegate.debugLogger,
1630 "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1631 app.setImageUrl(null);
1632 app.setThumbnail(null);
1634 logger.debug(EELFLoggerDelegate.debugLogger,
1635 "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1640 protected String constructImageName(OnboardingApp onboardingApp) {
1641 String appLandingPageURL = onboardingApp.getLandingPage();
1642 if(appLandingPageURL == null) {
1643 appLandingPageURL = "";
1645 return "portal_" + String.valueOf(appLandingPageURL.hashCode() + "_" + (int) (Math.random() * 100000.0))
1649 // Don't encrypt or decrypt the password if it is null or the empty string
1650 private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1652 if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) {
1654 result = CipherUtil.decryptPKC(encryptedAppPwd,
1655 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1656 } catch (Exception e) {
1657 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1663 protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1665 if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) {
1667 result = CipherUtil.encryptPKC(decryptedAppPwd,
1668 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1669 } catch (Exception e) {
1670 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1676 @SuppressWarnings("unchecked")
1678 public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1679 FieldsValidator fieldsValidator = new FieldsValidator();
1680 final Map<String, Long> params = new HashMap<>();
1681 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1684 params.put("userId", user.getId());
1685 epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1686 Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1687 for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1688 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1690 for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1691 if (epWidgetsManPref.getWidgetid() != null) {
1692 Long widgetid = epWidgetsManPref.getWidgetid();
1693 if (existingWidgetsIds.containsKey(widgetid)) {
1694 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1695 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1696 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1697 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1698 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1699 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1700 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1701 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1703 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1704 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1705 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1706 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1707 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1708 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1709 epWidgetsManualSort.setUserId(user.getId());
1710 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1712 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1715 } catch (Exception e) {
1716 logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1717 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1719 return fieldsValidator;
1722 @SuppressWarnings("unchecked")
1724 public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1725 FieldsValidator fieldsValidator = new FieldsValidator();
1726 final Map<String, Long> params = new HashMap<>();
1727 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1729 params.put("userId", user.getId());
1730 epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1731 Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1732 for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1733 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1735 for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1736 if (delEpWidgetsManPref.getWidgetid() != null) {
1737 Long widgetId = delEpWidgetsManPref.getWidgetid();
1738 if (existingWidgetIds.containsKey(widgetId)) {
1739 params.put("widgetId",widgetId);
1740 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1742 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1745 } catch (Exception e) {
1746 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1747 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1749 return fieldsValidator;
1753 * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1755 * @param: appsSortManual--contains User Apps Data
1757 * @param: user--contains LoggedIn User Data
1759 @SuppressWarnings("unchecked")
1761 public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1762 FieldsValidator fieldsValidator = new FieldsValidator();
1763 final Map<String, Long> params = new HashMap<>();
1764 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1767 params.put("userId", user.getId());
1768 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1769 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1770 for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1771 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1773 for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1774 if (epAppsManPref.getAppid() != null) {
1775 Long appid = epAppsManPref.getAppid();
1776 if (existingAppIds.containsKey(appid)) {
1777 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1779 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1780 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1781 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1782 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1784 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1785 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1787 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1788 epAppsManualSort.setUserId(user.getId());
1789 dataAccessService.saveDomainObject(epAppsManualSort, null);
1791 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1794 } catch (Exception e) {
1795 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1796 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1798 return fieldsValidator;
1804 * @see org.onap.portalapp.portal.service.EPAppService#
1805 * deleteUserAppSortManual(java.lang.String,
1806 * org.onap.portalapp.portal.domain.EPUser)
1808 @SuppressWarnings("unchecked")
1810 public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1811 FieldsValidator fieldsValidator = new FieldsValidator();
1812 final Map<String, Long> params = new HashMap<>();
1813 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1815 params.put("userId", user.getId());
1816 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1817 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1818 for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1819 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1821 if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1822 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1823 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1824 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1826 } catch (Exception e) {
1827 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1828 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1830 return fieldsValidator;
1833 @SuppressWarnings("unchecked")
1835 public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1836 FieldsValidator fieldsValidator = new FieldsValidator();
1837 final Map<String, Long> params = new HashMap<>();
1838 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1839 EPUserAppsSortPreference usrSortPr = null;
1841 params.put("userId", user.getId());
1842 epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1843 if (epSortTypes.size() == 0) {
1844 usrSortPr = new EPUserAppsSortPreference();
1845 usrSortPr.setUserId((int)(long)(user.getId()));
1846 usrSortPr.setSortPref(appsSortPreference.getValue());
1847 dataAccessService.saveDomainObject(usrSortPr, null);
1848 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1850 usrSortPr = epSortTypes.get(0);
1851 usrSortPr.setSortPref(appsSortPreference.getValue());
1852 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1853 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1854 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1855 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1857 } catch (Exception e) {
1858 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1859 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1861 return fieldsValidator;
1864 @SuppressWarnings("unchecked")
1866 public String getUserAppsSortTypePreference(EPUser user) {
1867 final Map<String, Long> params = new HashMap<>();
1868 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1870 params.put("userId", user.getId());
1871 userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1872 if (userSortPrefs.size() > 0)
1873 return userSortPrefs.get(0).getSortPref();
1876 } catch (Exception e) {
1877 logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1884 public List<EPApp> getUserRemoteApps(String id) {
1885 throw new RuntimeException(" Cannot be called from parent class");
1889 public UserRoles getUserProfileForLeftMenu(String loginId) {
1890 final Map<String, String> params = new HashMap<>();
1891 params.put("org_user_id", loginId);
1892 @SuppressWarnings("unchecked")
1893 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1894 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1895 if (usersRolesList == null || usersRolesList.size() < 1)
1898 return usersRolesList.get(0);
1903 public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1904 final Map<String, String> params = new HashMap<>();
1905 params.put("org_user_id", loginId);
1906 @SuppressWarnings("unchecked")
1907 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1908 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1909 if (usersRolesList == null || usersRolesList.size() < 1)
1912 return usersRolesList.get(0);
1916 public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1918 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1919 // If no roles are defined, treat this user as a guest.
1920 if (user.isGuest() || userAndRoles == null) {
1921 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1923 userAndRoles = createUserRoles(user);
1926 return userAndRoles;
1930 public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1932 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1933 // If no roles are defined, treat this user as a guest.
1934 if (user.isGuest() || userAndRoles == null) {
1935 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1937 userAndRoles = createUserRoles(user);
1940 return userAndRoles;
1944 public UserRoles createUserRoles(EPUser user)
1946 UserRole userRole = new UserRole();
1947 userRole.setUser_Id(user.getId());
1948 userRole.setOrgUserId(user.getLoginId());
1949 userRole.setFirstName(user.getFirstName());
1950 userRole.setLastName(user.getLastName());
1951 userRole.setRoleId(-1L);
1952 userRole.setRoleName("Guest");
1953 userRole.setUser_Id(-1L);
1954 UserRoles userAndRoles = new UserRoles(userRole);
1955 return userAndRoles;
1959 @SuppressWarnings("unused")
1961 public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception {
1962 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1963 HttpEntity<String> entity = new HttpEntity<>(headers);
1964 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace);
1965 ResponseEntity<String> response = null;
1968 String namespaceUrl = SystemProperties.
1969 getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "nss/" + namespace;
1971 response = template.exchange(namespaceUrl, HttpMethod.GET, entity, String.class);
1972 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace ,
1973 response.getStatusCode().value());
1974 if (response.getStatusCode().value() == 200) {
1975 String res = response.getBody();
1976 JSONObject jsonObj = new JSONObject(res);
1977 JSONArray namespaceArray = jsonObj.getJSONArray("ns");
1978 if(!namespaceArray.getJSONObject(0).has("admin")){
1979 logger.error(EELFLoggerDelegate.errorLogger,
1980 "No admins are available for requested namespace:" + namespace);
1981 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1982 "Portal Mechid is not an admin of" + namespace);
1985 JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin");
1986 ArrayList<String> list = new ArrayList<String>();
1987 if (namespaceAdminArray != null) {
1988 int len = namespaceAdminArray.length();
1989 for (int i = 0; i < len; i++) {
1990 list.add(namespaceAdminArray.get(i).toString());
1993 logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list);
1994 final String userName = SystemProperties
1995 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
1996 boolean idExists = list.stream().anyMatch(t -> userName.equals(t));
1998 logger.error(EELFLoggerDelegate.errorLogger,
1999 "Portal mechid is not admin of requested namespace:" + namespace);
2000 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
2001 "Portal Mechid is not an admin of" + namespace);
2005 } catch (HttpClientErrorException e) {
2006 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
2007 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());