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);
947 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
950 return fieldsValidator;
954 public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
955 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
956 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
957 validateOnboardingApp(newOnboardingApp, fieldsValidator);
959 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
960 if (newOnboardingApp.getId() == null) {
961 updateApp(null, newOnboardingApp, fieldsValidator, user);
963 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
966 return fieldsValidator;
969 @SuppressWarnings("unchecked")
971 public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
972 FieldsValidator fieldsValidator = new FieldsValidator();
973 if (!adminRolesService.isSuperAdmin(user)) {
974 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
975 return fieldsValidator;
977 final Map<String, Long> params = new HashMap<>();
978 params.put("app_id", appid);
980 //Checking if App is associated with any exiting microservices- ep_microservice:
981 final Map<String, Long> queryparams = new HashMap<>();
982 queryparams.put("applicationId", appid);
983 List<MicroserviceData> microservicesList = dataAccessService.executeNamedQuery( "getMicroservicesByAppId", queryparams, null);
984 if(microservicesList!=null && microservicesList.size()>0) {
985 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
986 return fieldsValidator;
989 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
990 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
991 for(int i=0;i<EPUserAppRolesRequestList.size();i++)
993 dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
996 Session localSession = null;
997 Transaction transaction = null;
998 Boolean result = false;
1000 localSession = sessionFactory.openSession();
1001 transaction = localSession.beginTransaction();
1003 // 1) Remove the URL for any functional menu item associated with
1005 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
1006 // Named query is stored in EP.hbm.xml, mapped to EPApp
1007 dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
1008 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted URL for any functional menu item associated with app");
1010 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
1011 // 2)Remove any favorites associated with a menu item that is
1012 // associated with this app
1013 dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
1014 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
1016 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
1017 // 3)Remove all role, appid records from fn_menu_functional_role
1018 // that are associated with this app
1019 dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
1020 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
1022 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1023 // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
1024 // that are associated with this app
1025 dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
1026 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1028 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
1029 // 5)Remove all rolefunctions, appid records from ep_app_function
1030 // that are associated with this app
1031 dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
1032 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
1034 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
1035 // 6)Remove all records from fn_user_role associated with this app
1036 dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
1037 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
1039 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
1040 // 7)Remove any widgets associated with this app
1041 dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
1042 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
1044 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
1045 // 8)Remove any roles associated with this app
1046 dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
1047 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
1049 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
1050 // 9)Remove all records from fn_role associated with this app
1051 dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
1052 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
1054 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
1055 // 10)Remove app contact us entries
1056 dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
1057 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
1059 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
1060 // 11)Remove rows in the app personalization selection table
1061 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
1062 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
1064 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
1065 // 12)Remove rows in the app personalization sort table
1066 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
1067 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
1069 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
1070 // 13)Remove rows in the app personalization sort table
1071 dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
1072 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
1074 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
1075 // 14)Remove rows in the ep_web_analytics_source
1076 dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
1077 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
1079 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
1080 // 15)Delete the app
1081 dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
1082 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
1085 // 1) Remove the URL for any functional menu item associated with
1087 String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
1088 + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
1090 Query query = localSession.createSQLQuery(sql);
1091 query.executeUpdate();
1093 // Remove any favorites associated with a menu item that is
1094 // associated with this app
1095 sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
1096 + " where fn_menu_functional_roles.app_id='" + appid + "' "
1097 + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
1099 query = localSession.createSQLQuery(sql);
1100 query.executeUpdate();
1102 // Remove all role, appid records from fn_menu_functional_role
1103 // that are associated with this app
1104 sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
1106 query = localSession.createSQLQuery(sql);
1107 query.executeUpdate();
1110 // Remove all roles, rolefunctions, appid records from ep_app_role_function
1111 // that are associated with this app
1112 sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
1113 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1114 query = localSession.createSQLQuery(sql);
1115 query.executeUpdate();
1117 //Remove all rolefunctions, appid records from ep_app_function
1118 // that are associated with this app
1119 sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
1120 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1121 query = localSession.createSQLQuery(sql);
1122 query.executeUpdate();
1124 // Remove all records from fn_user_role associated with this app
1125 sql = "delete from fn_user_role where app_id='" + appid + "'";
1127 query = localSession.createSQLQuery(sql);
1128 query.executeUpdate();
1130 // Remove any widgets associated with this app
1131 sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
1133 query = localSession.createSQLQuery(sql);
1134 query.executeUpdate();
1136 // Remove any roles associated with this app
1137 sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
1138 + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
1140 query = localSession.createSQLQuery(sql);
1141 query.executeUpdate();
1143 // Remove all records from fn_role associated with this app
1144 sql = "delete from fn_role where app_id='" + appid + "'";
1146 query = localSession.createSQLQuery(sql);
1147 query.executeUpdate();
1149 // Remove app contact us entries
1150 sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
1152 query = localSession.createSQLQuery(sql);
1153 query.executeUpdate();
1155 // Remove rows in the app personalization selection table
1156 sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
1158 query = localSession.createSQLQuery(sql);
1159 query.executeUpdate();
1161 // Remove rows in the app personalization sort table
1162 sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
1164 query = localSession.createSQLQuery(sql);
1165 query.executeUpdate();
1167 // Remove rows in the app personalization sort table
1168 sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
1170 query = localSession.createSQLQuery(sql);
1171 query.executeUpdate();
1173 // Remove rows in the app personalization sort table
1174 sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
1176 query = localSession.createSQLQuery(sql);
1177 query.executeUpdate();
1180 sql = "delete from fn_app where app_id='" + appid + "'";
1182 query = localSession.createSQLQuery(sql);
1183 query.executeUpdate();
1185 transaction.commit();
1188 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
1189 } catch (Exception e) {
1190 logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
1191 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
1192 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
1194 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
1197 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1199 return fieldsValidator;
1202 private static Object syncRests = new Object();
1204 // An app has been enabled/disabled. Must enable/disable all associated
1205 // functional menu items.
1206 protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1207 String active_yn = enabled ? "Y" : "N";
1208 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1209 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1210 + " AND r.app_id = '" + appId + "' ";
1212 @SuppressWarnings("unchecked")
1213 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1214 for (FunctionalMenuItem menuItem : menuItems) {
1215 FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1217 myMenuItem.active_yn = active_yn;
1218 localSession.save(myMenuItem);
1222 // Attention! If (appId == null) we use this function to create application
1223 // otherwise we use it to modify existing application
1224 protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1225 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1226 // Separate out the code for a restricted app, since it doesn't need any
1228 if (Boolean.TRUE.equals(onboardingApp.getRestrictedApp())) {
1229 boolean result = false;
1230 Session localSession = null;
1231 Transaction transaction = null;
1233 localSession = sessionFactory.openSession();
1234 transaction = localSession.beginTransaction();
1236 if (appId == null) {
1239 app = (EPApp) localSession.get(EPApp.class, appId);
1240 if (app == null || app.getId() == null) { // App is already
1242 transaction.commit();
1243 localSession.close();
1244 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1248 createAppFromOnboarding(app, onboardingApp, localSession);
1249 localSession.saveOrUpdate(app);
1250 // Enable or disable all menu items associated with this app
1251 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1252 transaction.commit();
1254 } catch (Exception e) {
1255 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1256 EcompPortalUtils.rollbackTransaction(transaction,
1257 "updateApp rollback, exception = " + e.toString());
1259 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1262 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1266 updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1272 protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1274 synchronized (syncRests) {
1275 boolean result = false;
1276 Session localSession = null;
1277 Transaction transaction = null;
1279 localSession = sessionFactory.openSession();
1280 transaction = localSession.beginTransaction();
1282 if (appId == null) {
1285 * In the parent class, the UEB code is responsible for generating the
1286 * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1287 * may be used in future at which point we can just remove this method and
1288 * depend on parent class's method So, using UUID generator to generate the
1289 * unique key instead.
1291 String uuidStr = UUID.randomUUID().toString();
1292 String appKey = uuidStr;
1293 String appSecret = uuidStr;
1294 String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1295 onboardingApp.setUebTopicName(appMailboxName);
1296 onboardingApp.setUebKey(appKey);
1297 onboardingApp.setUebSecret(appSecret);
1299 app = (EPApp) localSession.get(EPApp.class, appId);
1300 if (app == null || app.getId() == null) {
1301 // App is already deleted!
1302 transaction.commit();
1303 localSession.close();
1304 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1308 logger.debug(EELFLoggerDelegate.debugLogger,
1309 "updateRestrictedApp: about to call createAppFromOnboarding");
1310 createAppFromOnboarding(app, onboardingApp, localSession);
1311 logger.debug(EELFLoggerDelegate.debugLogger,
1312 "updateRestrictedApp: finished calling createAppFromOnboarding");
1313 localSession.saveOrUpdate(app);
1314 logger.debug(EELFLoggerDelegate.debugLogger,
1315 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1316 // Enable or disable all menu items associated with this app
1317 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1318 logger.debug(EELFLoggerDelegate.debugLogger,
1319 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1320 transaction.commit();
1321 logger.debug(EELFLoggerDelegate.debugLogger,
1322 "updateRestrictedApp: finished calling transaction.commit");
1324 } catch (Exception e) {
1325 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1326 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1327 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1328 EcompPortalUtils.rollbackTransaction(transaction,
1329 "updateRestrictedApp rollback, exception = " + e.toString());
1331 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1334 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1341 protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1343 synchronized (syncRests) {
1344 boolean result = false;
1345 Session localSession = null;
1346 Transaction transaction = null;
1348 localSession = sessionFactory.openSession();
1349 transaction = localSession.beginTransaction();
1351 if (appId == null) {
1353 // -------------------------------------------------------------------------------------------
1354 // Register this App with the UEB communication server.
1356 // the App's unique mailbox/topic
1357 // name and keys to the FN_APP table. The App's mailbox
1359 // keys will be visible to the
1360 // admin on the ONAP portal.
1361 // -------------------------------------------------------------------------------------------
1362 TopicManager topicManager = new TopicManager() {
1364 EPAppCommonServiceImpl service;
1366 public void init(EPAppCommonServiceImpl _service) {
1370 public void createTopic(String key, String secret, String topicName,
1371 String topicDescription) throws HttpException, CambriaApiException, IOException {
1373 init(EPAppCommonServiceImpl.this);
1374 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1375 if (logger.isInfoEnabled()) {
1376 logger.info("==> createTopic");
1377 logger.info("topicName: " + topicName);
1378 logger.info("topicDescription: " + topicDescription);
1380 CambriaTopicManager tm = null;
1382 tm = service.getTopicManager(urlList, key, secret);
1383 } catch (Exception e) {
1384 logger.error("pub.build Exception ", e);
1385 throw new CambriaApiException(topicName);
1387 tm.createTopic(topicName, topicDescription, 1, 1);
1390 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1391 String topicName) throws HttpException, CambriaApiException, IOException {
1392 logger.info("==> addPublisher to topic " + topicName);
1393 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1394 CambriaTopicManager tm = null;
1396 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1397 } catch (Exception e) {
1398 logger.error("pub.build Exception ", e);
1399 throw new CambriaApiException(topicName);
1401 tm.allowProducer(topicName, publisherKey);
1405 final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1406 .usingHosts(Helper.uebUrlList()).build();
1407 com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1408 "ONAP Portal Owner");
1409 String appKey = credential.getApiKey();
1410 String appSecret = credential.getApiSecret();
1411 String appMailboxName = null;
1413 int maxNumAttemptsToCreateATopic = 3;
1414 boolean successfullyCreatedMailbox = false;
1415 for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1416 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1419 topicManager.createTopic(
1420 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1421 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1422 appMailboxName, "ECOMP outbox for app" + onboardingApp.getAppName());
1423 successfullyCreatedMailbox = true;
1424 logger.debug(EELFLoggerDelegate.debugLogger,
1425 "Successfully created " + appMailboxName + " for App " + onboardingApp.getAppName());
1426 logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
1427 + appSecret + " generated using = " + user.getEmail());
1429 } catch (HttpException e) {
1430 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1431 if (e.getStatusCode() == 409) {
1432 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1433 + " already exists. Will try using a different name", e);
1435 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1441 if (successfullyCreatedMailbox) {
1442 onboardingApp.setUebTopicName(appMailboxName);
1443 onboardingApp.setUebKey(appKey);
1444 onboardingApp.setUebSecret(appSecret);
1448 * EP is a publisher to this App's new mailbox
1450 topicManager.addPublisher(
1451 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1452 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1453 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1457 * This App is a subscriber of its own mailbox
1459 topicManager.addSubscriber(
1460 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1461 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1465 * This App is a publisher to EP
1467 topicManager.addPublisher(
1468 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1469 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1470 PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1471 } catch (HttpException | CambriaApiException | IOException e) {
1472 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1473 logger.error(EELFLoggerDelegate.errorLogger,
1474 "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1475 transaction.commit();
1476 localSession.close();
1477 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1481 transaction.commit();
1482 localSession.close();
1483 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1487 app = (EPApp) localSession.get(EPApp.class, appId);
1488 if (app == null || app.getId() == null) {
1489 // App is already deleted!
1490 transaction.commit();
1491 localSession.close();
1492 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1496 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1497 createAppFromOnboarding(app, onboardingApp, localSession);
1498 logger.debug(EELFLoggerDelegate.debugLogger,
1499 "LR: updateApp: finished calling createAppFromOnboarding");
1500 localSession.saveOrUpdate(app);
1501 logger.debug(EELFLoggerDelegate.debugLogger,
1502 "LR: updateApp: finished calling localSession.saveOrUpdate");
1503 // Enable or disable all menu items associated with this app
1504 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1505 logger.debug(EELFLoggerDelegate.debugLogger,
1506 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1507 transaction.commit();
1508 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1509 logger.debug(EELFLoggerDelegate.debugLogger,
1510 "LR: updateApp: finished calling epUebHelper.addPublisher");
1512 } catch (Exception e) {
1513 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1514 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1515 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1516 EcompPortalUtils.rollbackTransaction(transaction,
1517 "updateApp rollback, exception = " + e.toString());
1519 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1522 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1528 public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1529 throws GeneralSecurityException, Exception {
1530 throw new Exception("This method can only be invoked from child class");
1534 * Populates a transport model of the application from a database row model.
1535 * Leaves out the thumbnail because the FE fetches images via a different
1539 * Model of database row
1540 * @param onboardingApp
1541 * Model for transport as JSON
1544 public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1545 onboardingApp.setId(app.getId());
1546 onboardingApp.setAppName(app.getName());
1547 onboardingApp.setImageUrl(app.getImageUrl());
1548 onboardingApp.setAppDescription(app.getAppDescription());
1549 onboardingApp.setAppNotes(app.getAppNotes());
1550 onboardingApp.setLandingPage(app.getLandingPage());
1551 onboardingApp.setAlternateLandingPage(app.getAlternateLandingPage());
1552 onboardingApp.setRestUrl(app.getAppRestEndpoint());
1553 onboardingApp.setIsOpen(app.getOpen());
1554 onboardingApp.setIsEnabled(app.getEnabled());
1555 onboardingApp.setAppBasicAuthUsername(app.getAppBasicAuthUsername());
1557 String effectivePwd = null;
1558 if (app.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1559 effectivePwd = EPCommonSystemProperties.APP_DISPLAY_PASSWORD;
1561 effectivePwd = decryptedPassword(app.getAppBasicAuthPassword(), app);
1563 onboardingApp.setAppBasicAuthPassword(effectivePwd);
1564 onboardingApp.setUebTopicName(app.getUebTopicName());
1565 onboardingApp.setUebKey(app.getUebKey());
1566 onboardingApp.setUebSecret(app.getUebSecret());
1567 onboardingApp.setRolesInAAF(app.getRolesInAAF());
1568 onboardingApp.setNameSpace(app.getNameSpace());
1569 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1570 onboardingApp.setModeOfIntegration(app.getModeOfIntegration());
1571 onboardingApp.setAppAck(app.getAppAck());
1572 onboardingApp.setUsesCadi(app.getUsesCadi());
1573 onboardingApp.setApplicationType(app.getAppType().toString());
1577 * Creates a database object for an application from an uploaded transport
1578 * model. Must decode the thumbnail, if any.
1581 * @param onboardingApp
1582 * @param localSession
1583 * @return The first argument.
1585 protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1586 app.setName(onboardingApp.getAppName());
1587 app.setAppDescription(onboardingApp.getAppDescription());
1588 app.setAppNotes(onboardingApp.getAppNotes());
1589 app.setLandingPage(onboardingApp.getLandingPage());
1590 app.setAlternateLandingPage(onboardingApp.getAlternateLandingPage());
1591 app.setAppRestEndpoint(onboardingApp.getRestUrl());
1592 app.setOpen(onboardingApp.getIsOpen());
1593 app.setEnabled(onboardingApp.getIsEnabled());
1594 app.setAppBasicAuthUsername(onboardingApp.getAppBasicAuthUsername());
1595 if(!onboardingApp.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1596 app.setAppBasicAuthPassword(this.encryptedPassword(onboardingApp.getAppBasicAuthPassword(), app));
1597 //app.setUebTopicName(onboardingApp.uebTopicName);
1598 app.setUebKey(onboardingApp.getUebKey());
1599 app.setUebSecret(onboardingApp.getUebSecret());
1600 app.setRolesInAAF(onboardingApp.getRolesInAAF());
1601 app.setNameSpace(onboardingApp.getNameSpace());
1602 app.setAppType(new Integer(onboardingApp.getApplicationType()));
1603 app.setModeOfIntegration(onboardingApp.getModeOfIntegration());
1604 app.setAppAck(onboardingApp.getAppAck());
1605 app.setUsesCadi(onboardingApp.getUsesCadi());
1608 if (!StringUtils.isEmpty(onboardingApp.getThumbnail())) {
1609 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1610 String[] splitBase64Thumbnail = onboardingApp.getThumbnail().split("base64,");
1611 logger.debug(EELFLoggerDelegate.debugLogger,
1612 "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1613 if (splitBase64Thumbnail.length > 1) {
1614 // This occurs when we have a new image, not an existing image
1615 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1616 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1617 // This is basically a boolean indicator that an image is
1619 app.setImageUrl(constructImageName(onboardingApp));
1620 app.setThumbnail(decodedImage);
1622 } else if (app.getThumbnail() != null && onboardingApp.getImageLink() == null) {
1623 // The thumbnail that came in from the json is empty; the previous
1624 // thumbnail is NOT empty. Must delete it.
1625 logger.debug(EELFLoggerDelegate.debugLogger,
1626 "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1627 app.setImageUrl(null);
1628 app.setThumbnail(null);
1630 logger.debug(EELFLoggerDelegate.debugLogger,
1631 "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1636 protected String constructImageName(OnboardingApp onboardingApp) {
1637 String appLandingPageURL = onboardingApp.getLandingPage();
1638 if(appLandingPageURL == null) {
1639 appLandingPageURL = "";
1641 return "portal_" + String.valueOf(appLandingPageURL.hashCode() + "_" + (int) (Math.random() * 100000.0))
1645 // Don't encrypt or decrypt the password if it is null or the empty string
1646 private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1648 if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) {
1650 result = CipherUtil.decryptPKC(encryptedAppPwd,
1651 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1652 } catch (Exception e) {
1653 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1659 protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1661 if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) {
1663 result = CipherUtil.encryptPKC(decryptedAppPwd,
1664 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1665 } catch (Exception e) {
1666 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1672 @SuppressWarnings("unchecked")
1674 public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1675 FieldsValidator fieldsValidator = new FieldsValidator();
1676 final Map<String, Long> params = new HashMap<>();
1677 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1680 params.put("userId", user.getId());
1681 epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1682 Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1683 for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1684 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1686 for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1687 if (epWidgetsManPref.getWidgetid() != null) {
1688 Long widgetid = epWidgetsManPref.getWidgetid();
1689 if (existingWidgetsIds.containsKey(widgetid)) {
1690 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1691 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1692 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1693 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1694 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1695 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1696 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1697 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1699 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1700 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1701 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1702 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1703 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1704 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1705 epWidgetsManualSort.setUserId(user.getId());
1706 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1708 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1711 } catch (Exception e) {
1712 logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1713 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1715 return fieldsValidator;
1718 @SuppressWarnings("unchecked")
1720 public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1721 FieldsValidator fieldsValidator = new FieldsValidator();
1722 final Map<String, Long> params = new HashMap<>();
1723 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1725 params.put("userId", user.getId());
1726 epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1727 Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1728 for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1729 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1731 for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1732 if (delEpWidgetsManPref.getWidgetid() != null) {
1733 Long widgetId = delEpWidgetsManPref.getWidgetid();
1734 if (existingWidgetIds.containsKey(widgetId)) {
1735 params.put("widgetId",widgetId);
1736 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1738 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1741 } catch (Exception e) {
1742 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1743 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1745 return fieldsValidator;
1749 * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1751 * @param: appsSortManual--contains User Apps Data
1753 * @param: user--contains LoggedIn User Data
1755 @SuppressWarnings("unchecked")
1757 public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1758 FieldsValidator fieldsValidator = new FieldsValidator();
1759 final Map<String, Long> params = new HashMap<>();
1760 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1763 params.put("userId", user.getId());
1764 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1765 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1766 for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1767 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1769 for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1770 if (epAppsManPref.getAppid() != null) {
1771 Long appid = epAppsManPref.getAppid();
1772 if (existingAppIds.containsKey(appid)) {
1773 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1775 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1776 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1777 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1778 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1780 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1781 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1783 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1784 epAppsManualSort.setUserId(user.getId());
1785 dataAccessService.saveDomainObject(epAppsManualSort, null);
1787 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1790 } catch (Exception e) {
1791 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1792 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1794 return fieldsValidator;
1800 * @see org.onap.portalapp.portal.service.EPAppService#
1801 * deleteUserAppSortManual(java.lang.String,
1802 * org.onap.portalapp.portal.domain.EPUser)
1804 @SuppressWarnings("unchecked")
1806 public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1807 FieldsValidator fieldsValidator = new FieldsValidator();
1808 final Map<String, Long> params = new HashMap<>();
1809 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1811 params.put("userId", user.getId());
1812 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1813 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1814 for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1815 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1817 if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1818 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1819 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1820 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1822 } catch (Exception e) {
1823 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1824 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1826 return fieldsValidator;
1829 @SuppressWarnings("unchecked")
1831 public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1832 FieldsValidator fieldsValidator = new FieldsValidator();
1833 final Map<String, Long> params = new HashMap<>();
1834 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1835 EPUserAppsSortPreference usrSortPr = null;
1837 params.put("userId", user.getId());
1838 epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1839 if (epSortTypes.size() == 0) {
1840 usrSortPr = new EPUserAppsSortPreference();
1841 usrSortPr.setUserId((int)(long)(user.getId()));
1842 usrSortPr.setSortPref(appsSortPreference.getValue());
1843 dataAccessService.saveDomainObject(usrSortPr, null);
1844 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1846 usrSortPr = epSortTypes.get(0);
1847 usrSortPr.setSortPref(appsSortPreference.getValue());
1848 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1849 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1850 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1851 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1853 } catch (Exception e) {
1854 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1855 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1857 return fieldsValidator;
1860 @SuppressWarnings("unchecked")
1862 public String getUserAppsSortTypePreference(EPUser user) {
1863 final Map<String, Long> params = new HashMap<>();
1864 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1866 params.put("userId", user.getId());
1867 userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1868 if (userSortPrefs.size() > 0)
1869 return userSortPrefs.get(0).getSortPref();
1872 } catch (Exception e) {
1873 logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1880 public List<EPApp> getUserRemoteApps(String id) {
1881 throw new RuntimeException(" Cannot be called from parent class");
1885 public UserRoles getUserProfileForLeftMenu(String loginId) {
1886 final Map<String, String> params = new HashMap<>();
1887 params.put("org_user_id", loginId);
1888 @SuppressWarnings("unchecked")
1889 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1890 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1891 if (usersRolesList == null || usersRolesList.size() < 1)
1894 return usersRolesList.get(0);
1899 public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1900 final Map<String, String> params = new HashMap<>();
1901 params.put("org_user_id", loginId);
1902 @SuppressWarnings("unchecked")
1903 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1904 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1905 if (usersRolesList == null || usersRolesList.size() < 1)
1908 return usersRolesList.get(0);
1912 public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1914 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1915 // If no roles are defined, treat this user as a guest.
1916 if (user.isGuest() || userAndRoles == null) {
1917 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1919 userAndRoles = createUserRoles(user);
1922 return userAndRoles;
1926 public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1928 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1929 // If no roles are defined, treat this user as a guest.
1930 if (user.isGuest() || userAndRoles == null) {
1931 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1933 userAndRoles = createUserRoles(user);
1936 return userAndRoles;
1940 public UserRoles createUserRoles(EPUser user)
1942 UserRole userRole = new UserRole();
1943 userRole.setUser_Id(user.getId());
1944 userRole.setOrgUserId(user.getLoginId());
1945 userRole.setFirstName(user.getFirstName());
1946 userRole.setLastName(user.getLastName());
1947 userRole.setRoleId(-1L);
1948 userRole.setRoleName("Guest");
1949 userRole.setUser_Id(-1L);
1950 UserRoles userAndRoles = new UserRoles(userRole);
1951 return userAndRoles;
1955 @SuppressWarnings("unused")
1957 public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception {
1958 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1959 HttpEntity<String> entity = new HttpEntity<>(headers);
1960 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace);
1961 ResponseEntity<String> response = null;
1964 String namespaceUrl = SystemProperties.
1965 getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "nss/" + namespace;
1967 response = template.exchange(namespaceUrl, HttpMethod.GET, entity, String.class);
1968 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace ,
1969 response.getStatusCode().value());
1970 if (response.getStatusCode().value() == 200) {
1971 String res = response.getBody();
1972 JSONObject jsonObj = new JSONObject(res);
1973 JSONArray namespaceArray = jsonObj.getJSONArray("ns");
1974 if(!namespaceArray.getJSONObject(0).has("admin")){
1975 logger.error(EELFLoggerDelegate.errorLogger,
1976 "No admins are available for requested namespace:" + namespace);
1977 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1978 "Portal Mechid is not an admin of" + namespace);
1981 JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin");
1982 ArrayList<String> list = new ArrayList<String>();
1983 if (namespaceAdminArray != null) {
1984 int len = namespaceAdminArray.length();
1985 for (int i = 0; i < len; i++) {
1986 list.add(namespaceAdminArray.get(i).toString());
1989 logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list);
1990 final String userName = SystemProperties
1991 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
1992 boolean idExists = list.stream().anyMatch(t -> userName.equals(t));
1994 logger.error(EELFLoggerDelegate.errorLogger,
1995 "Portal mechid is not admin of requested namespace:" + namespace);
1996 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1997 "Portal Mechid is not an admin of" + namespace);
2001 } catch (HttpClientErrorException e) {
2002 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
2003 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());