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;
118 import java.security.SecureRandom;
121 public class EPAppCommonServiceImpl implements EPAppService {
123 protected String ECOMP_APP_ID = "1";
124 protected String SUPER_ADMIN_ROLE_ID = "1";
125 protected String ACCOUNT_ADMIN_ROLE_ID = "999";
126 protected String RESTRICTED_APP_ROLE_ID = "900";
128 //private static final String urlField = "url";
129 private static final String nameSpaceField = "url";
131 private static final String nameField = "name";
133 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
136 private AdminRolesService adminRolesService;
138 protected SessionFactory sessionFactory;
140 private DataAccessService dataAccessService;
142 RestTemplate template = new RestTemplate();
145 private void init() {
146 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
147 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
148 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
149 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
152 public Boolean onboardingAppFieldsValidation(OnboardingApp onboardingApp) {
153 //FieldsValidator fieldsValidator = new FieldsValidator();
155 if ((!onboardingApp.getRestrictedApp()) &&( onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0 || onboardingApp.getRestrictedApp() == null
156 || onboardingApp.getLandingPage() == null || onboardingApp.getLandingPage().length() == 0 || onboardingApp.getRestUrl() == null || onboardingApp.getRestUrl().length() == 0
157 || onboardingApp.getAppBasicAuthUsername() == null || onboardingApp.getAppBasicAuthUsername().length() == 0
158 || onboardingApp.getIsOpen() == null
159 || (onboardingApp.getId() != null && onboardingApp.getId().equals(ECOMP_APP_ID)))
160 // For a normal app (appType == PortalConstants.PortalAppId),
161 // these fields must be filled
163 // For a restricted app (appType==2), they will be empty.
164 || ((onboardingApp.getRestrictedApp()) && (onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0
165 || onboardingApp.getLandingPage() == null || onboardingApp.getLandingPage().length() == 0 || onboardingApp.getIsOpen() == null))) {
172 private Boolean onboardingInactiveAppFieldsForValidation(OnboardingApp onboardingApp) {
173 if (onboardingApp.getAppName() == null || onboardingApp.getAppName().length() == 0
174 || onboardingApp.getIsOpen() == null) {
180 protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
181 FieldsValidator fieldsValidator = new FieldsValidator();
182 if (onboardingApp.getRolesInAAF()) {
183 if (!onboardingApp.getIsEnabled()) {
184 if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
185 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
187 } else if (onboardingApp.getIsEnabled()) {
188 if (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.getNameSpace() == null
189 || onboardingApp.getNameSpace().length() == 0) {
190 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
194 if (!onboardingApp.getIsEnabled()) {
195 if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
196 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
198 } else if (onboardingApp.getIsEnabled()) {
199 if(onboardingApp.getRestrictedApp() && onboardingAppFieldsValidation(onboardingApp) == false){
200 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
202 else if (!onboardingApp.getRestrictedApp() && (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.getAppBasicAuthPassword() == null
203 || onboardingApp.getAppBasicAuthPassword().length() == 0)) {
204 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
208 return fieldsValidator;
214 public List<EPApp> getUserAsAdminApps(EPUser user) {
215 if (adminRolesService.isAccountAdmin(user)) {
216 String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
217 + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
218 + " AND FN_APP.ENABLED = 'Y'";
221 @SuppressWarnings("unchecked")
222 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
224 } catch (Exception e) {
225 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
230 logger.error(EELFLoggerDelegate.errorLogger,
231 "getUserAsAdminApps: only Account Admin may invoke this function!");
232 return new ArrayList<EPApp>();
239 public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
240 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
241 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
242 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
243 + " AND FN_APP.ENABLED = 'Y'";
245 String sql = String.format(format, orgUserId);
249 @SuppressWarnings("unchecked")
250 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
252 } catch (Exception e) {
253 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
259 public List<EPApp> getAppsFullList() {
260 @SuppressWarnings("unchecked")
261 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
266 public List<EcompApp> getEcompAppAppsFullList() {
267 return transformAppsToEcompApps(getAppsFullList());
271 public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
272 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
273 for (EPApp app : appsList) {
274 EcompApp ecompApp = new EcompApp();
275 ecompApp.setId(app.getId());
276 ecompApp.setName(app.getName());
277 ecompApp.setImageUrl(app.getImageUrl());
278 ecompApp.setDescription(app.getAppDescription());
279 ecompApp.setNotes(app.getAppNotes());
280 ecompApp.setUrl(app.getLandingPage());
281 ecompApp.setAlternateUrl(app.getAlternateLandingPage());
282 ecompApp.setUebTopicName(app.getUebTopicName());
283 //ecompApp.setUebKey(app.getUebKey());
284 ecompApp.setUebSecret(app.getUebSecret());
285 ecompApp.setEnabled(app.getEnabled());
286 ecompApp.setCentralAuth(app.getRolesInAAF());
287 ecompApp.setNameSpace(app.getNameSpace());
288 ecompApp.setRestrictedApp(app.isRestrictedApp());
289 ecompAppList.add(ecompApp);
295 public EPApp getApp(Long appId) {
297 return (EPApp) dataAccessService.getDomainObject(EPApp.class, appId, null);
298 } catch (Exception e) {
299 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
306 @SuppressWarnings("unchecked")
308 public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
310 if (adminRolesService.isAccountAdmin(user) && adminRolesService.isRoleAdmin(user)) {
311 final Map<String, Long> params = new HashMap<>();
312 params.put("userId", user.getId());
313 List applicationRoleswithAccountandRoleadmin = dataAccessService
314 .executeNamedQuery("getApplicationsofTheUserwithAdminAndRoleAdmin", params, null);
316 return applicationRoleswithAccountandRoleadmin;
317 } catch (Exception e) {
318 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
319 logger.error(EELFLoggerDelegate.errorLogger,
320 "Exception occurred while fetching the list of user who has type account and role approver "
327 if (adminRolesService.isAccountAdmin(user)) {
328 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 "
329 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
330 + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
331 String sql = String.format(format, user.getId());
334 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
335 } catch (Exception e) {
336 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
337 logger.error(EELFLoggerDelegate.errorLogger,
338 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
343 if (adminRolesService.isRoleAdmin(user)) {
344 final Map<String, Long> params = new HashMap<>();
345 params.put("userId", user.getId());
346 List applicationRoles = dataAccessService.executeNamedQuery("getApplicationsofTheUserContainsApprover",
350 return applicationRoles;
351 } catch (Exception e) {
352 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
353 logger.error(EELFLoggerDelegate.errorLogger,
354 "Exception occurred while fetching the list of user who has type approver "
361 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
362 // app.APP_REST_ENDPOINT <> ''";
364 return new ArrayList<AppIdAndNameTransportModel>();
368 public EPApp getAppDetail(String appName) {
369 final Map<String, String> params = new HashMap<String, String>();
371 params.put("appName", appName);
372 @SuppressWarnings("unchecked")
373 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
374 return (apps.size() > 0) ? apps.get(0) : null;
375 } catch(Exception e) {
376 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
382 public EPApp getAppDetailByAppName(String appName) {
383 final Map<String, String> params = new HashMap<String, String>();
385 params.put("appName", appName);
386 @SuppressWarnings("unchecked")
387 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getAppDetailsByAppName", params, null);
388 if (apps.size() > 0) {
389 EPApp app = apps.get(0);
390 if (!EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
391 app.setRolesInAAF(false);
397 } catch (Exception e) {
398 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
403 @SuppressWarnings("unchecked")
405 public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
406 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
409 if (adminRolesService.isSuperAdmin(user)) {
410 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
411 + "where app.ENABLED = 'Y' AND app.app_type = 1";
413 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 "
414 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
415 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
417 sql = String.format(format, user.getId());
418 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
419 // app.APP_REST_ENDPOINT <> ''";
422 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
423 } catch (Exception e) {
424 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
425 logger.error(EELFLoggerDelegate.errorLogger,
426 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
429 return new ArrayList<AppIdAndNameTransportModel>();
432 protected void logQuery(String sql) {
433 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
436 public DataAccessService getDataAccessService() {
437 return dataAccessService;
440 public void setDataAccessService(DataAccessService dataAccessService) {
441 this.dataAccessService = dataAccessService;
444 @SuppressWarnings("unchecked")
446 public List<AdminUserApplications> getAppsAdmins() {
448 Map<String, String> params = new HashMap<>();
449 params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
450 List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
452 return aggregateRowsResultsByUserId(adminApps);
453 } catch (Exception e) {
454 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
459 private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
460 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
461 for (AdminUserApp app : adminApps) {
462 Long userId = app.getUser_Id();
463 if (adminUserApplications.get(userId) == null)
464 adminUserApplications.put(userId, new AdminUserApplications(app));
466 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
468 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
472 public List<AppsResponse> getAllApps(Boolean all) {
473 // If all is true, return both active and inactive apps. Otherwise, just
475 @SuppressWarnings("unchecked")
476 // Sort the list by application name so the drop-down looks pretty.
477 List<EPApp> apps = all
478 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
479 : (List<EPApp>) dataAccessService.getList(EPApp.class,
480 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
482 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
483 for (EPApp app : apps) {
484 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
491 public List<AppsResponse> getAllApplications(Boolean all) {
492 // If all is true, return both active and inactive apps. Otherwise, just
494 @SuppressWarnings("unchecked")
495 // Sort the list by application name so the drop-down looks pretty.
496 List<EPApp> apps = all
497 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
498 :dataAccessService.getList(EPApp.class, null);
500 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
501 for (EPApp app : apps) {
502 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
507 public UserRoles getUserProfile(String loginId) {
508 final Map<String, String> params = new HashMap<>();
509 params.put("org_user_id", loginId);
510 @SuppressWarnings("unchecked")
511 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
512 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
513 if (usersRolesList == null || usersRolesList.size() < 1)
516 return usersRolesList.get(0);
520 public UserRoles getUserProfileNormalized(EPUser user) {
522 UserRoles userAndRoles = getUserProfile(user.getLoginId());
523 // If no roles are defined, treat this user as a guest.
524 if (user.isGuest() || userAndRoles == null) {
525 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
527 UserRole userRole = new UserRole();
528 userRole.setUser_Id(user.getId());
529 userRole.setOrgUserId(user.getLoginId());
530 userRole.setFirstName(user.getFirstName());
531 userRole.setLastName(user.getLastName());
532 userRole.setRoleId(-1L);
533 userRole.setRoleName("Guest");
534 userRole.setUser_Id(-1L);
535 userAndRoles = new UserRoles(userRole);
541 protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
542 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
543 for (UserRole user : userRoleList) {
544 String orgUserId = user.getOrgUserId();
545 if (userRoles.get(orgUserId) == null)
546 userRoles.put(orgUserId, new UserRoles(user));
548 userRoles.get(orgUserId).addRole(user.getRoleName());
550 return new ArrayList<UserRoles>(userRoles.values());
553 private boolean isRestrictedApp(Long appId) {
554 EPApp app = getApp(appId);
555 return app.isRestrictedApp();
558 // For the functional menu edit
560 public List<LocalRole> getAppRoles(Long appId) {
562 if (isRestrictedApp(appId)) {
563 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
564 }else if(appId == 1){
565 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
567 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
570 @SuppressWarnings("unchecked")
571 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
575 protected String userAppsQuery(EPUser user) {
576 StringBuilder query = new StringBuilder();
577 if (adminRolesService.isSuperAdmin(user)) {
578 query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
580 query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
582 "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
583 query.append(" AND FN_APP.ENABLED = 'Y'");
585 return query.toString();
588 /*protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
589 FieldsValidator fieldsValidator = new FieldsValidator();
590 if(onboardingApp.isCentralAuth){
591 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
592 || onboardingApp.url.length() == 0 || onboardingApp.getRestrictedApp() == null
593 || onboardingApp.getIsOpen() == null || onboardingApp.getIsEnabled() == null
594 || (onboardingApp.getId() != null && ECOMP_APP_ID.equals(onboardingApp.getId().toString()))
595 // For a normal app (appType == PortalConstants.PortalAppId),
596 // these fields must be filled
598 // For a restricted app (appType==2), they will be empty.
599 || ((!onboardingApp.getRestrictedApp()) && (onboardingApp.myLoginsAppName == null
600 || onboardingApp.myLoginsAppName.length() == 0 || onboardingApp.myLoginsAppOwner == null
601 || onboardingApp.myLoginsAppOwner.length() == 0 || onboardingApp.username == null
602 || onboardingApp.username.length() == 0 ))) {
603 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
607 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
608 || onboardingApp.url.length() == 0 || onboardingApp.getRestrictedApp() == null
609 || onboardingApp.getIsOpen() == null || onboardingApp.getIsEnabled() == null
610 || (onboardingApp.getId() != null && ECOMP_APP_ID.equals(onboardingApp.getId().toString()))
611 // For a normal app (appType == PortalConstants.PortalAppId),
612 // these fields must be filled
614 // For a restricted app (appType==2), they will be empty.
615 || ((!onboardingApp.getRestrictedApp()) && (onboardingApp.myLoginsAppName == null
616 || onboardingApp.myLoginsAppName.length() == 0 || onboardingApp.myLoginsAppOwner == null
617 || onboardingApp.myLoginsAppOwner.length() == 0 || onboardingApp.username == null
618 || onboardingApp.username.length() == 0 || onboardingApp.appPassword == null
619 || onboardingApp.appPassword.length() == 0))) {
620 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
625 return fieldsValidator;
629 public List<EPApp> getUserApps(EPUser user) {
630 List<EPApp> openApps = getOpenApps();
632 if (user.isGuest()) {
635 String sql = userAppsQuery(user);
638 // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
639 List<EPApp> appsList = new ArrayList<>();
640 @SuppressWarnings("unchecked")
641 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
642 HashSet<EPApp> appSet = new HashSet<>();
643 for (EPApp app : adminApps) {
648 for (EPApp app : openApps) {
649 if (!appSet.contains(app))
658 public List<EPApp> getPersAdminApps(EPUser user) {
659 final Map<String, Long> params = new HashMap<>();
660 params.put("userId", user.getId());
661 // Named query is stored in EP.hbm.xml, mapped to EPApp
662 @SuppressWarnings("unchecked")
663 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
668 public List<EPApp> getPersUserApps(EPUser user) {
669 final Map<String, Long> params = new HashMap<>();
670 params.put("userId", user.getId());
671 // Named query is stored in EP.hbm.xml, mapped to EPApp
672 @SuppressWarnings("unchecked")
673 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
681 * org.onap.portalapp.portal.service.EPAppService#getAppCatalog(
682 * org.onap.portalapp.portal.domain.EPUser)
685 public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
686 final Map<String, Long> params = new HashMap<>();
687 params.put("userId", user.getId());
688 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
689 @SuppressWarnings("unchecked")
690 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
698 * org.onap.portalapp.portal.service.EPAppService#getAdminAppCatalog(
699 * org.onap.portalapp.portal.domain.EPUser)
702 public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
703 final Map<String, Long> params = new HashMap<>();
704 params.put("userId", user.getId());
705 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
706 @SuppressWarnings("unchecked")
707 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
711 private List<EPApp> getOpenApps() {
712 @SuppressWarnings("unchecked")
713 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
717 @SuppressWarnings("unchecked")
719 public List<EPApp> getAppsOrderByName(EPUser user) {
720 final Map<String, Long> params = new HashMap<>();
721 List<EPApp> sortedAppsByName = null;
723 if (adminRolesService.isSuperAdmin(user)) {
724 params.put("userId", user.getId());
725 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
727 params.put("userId", user.getId());
728 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
730 } catch (Exception e) {
731 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
733 return sortedAppsByName;
736 @SuppressWarnings("unchecked")
738 public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
740 final Map<String, Long> params = new HashMap<>();
741 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
742 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
744 if (adminRolesService.isSuperAdmin(user)) {
745 params.put("userId", user.getId());
746 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
748 params.put("userId", user.getId());
749 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
751 Set<String> epAppSet = new HashSet<String>();
752 for (EPApp eapp : sortedAppsByLastUsed)
753 if (!epAppSet.contains(eapp.getName())) {
754 finalsortedAppsByLastUsed.add(eapp);
755 epAppSet.add(eapp.getName());
758 } catch (Exception e) {
759 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
761 return finalsortedAppsByLastUsed;
764 @SuppressWarnings("unchecked")
766 public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
767 final Map<String, Long> params = new HashMap<>();
768 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
769 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
771 if (adminRolesService.isSuperAdmin(user)) {
772 params.put("userId", user.getId());
773 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
775 params.put("userId", user.getId());
776 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
778 Set<String> epAppSet = new HashSet<String>();
780 for (EPApp eapp : sortedAppsByMostUsed) {
781 if (!epAppSet.contains(eapp.getName())) {
782 finalsortedAppsByMostUsed.add(eapp);
783 epAppSet.add(eapp.getName());
786 } catch (Exception e) {
787 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
790 return finalsortedAppsByMostUsed;
794 * This Method retrieves the User Apps by Sort Manual Preference
796 * @param: user--contains LoggedIn User Data
798 @SuppressWarnings("unchecked")
800 public List<EPApp> getAppsOrderByManual(EPUser user) {
801 final Map<String, Long> params = new HashMap<>();
802 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
803 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
805 if (adminRolesService.isSuperAdmin(user)) {
806 params.put("userId", user.getId());
807 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
809 params.put("userId", user.getId());
810 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
812 Set<String> epAppSet = new HashSet<String>();
814 for (EPApp eapp : sortedAppsByManual) {
815 if (!epAppSet.contains(eapp.getName())) {
816 finalsortedAppsByManual.add(eapp);
817 epAppSet.add(eapp.getName());
820 } catch (Exception e) {
821 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
823 return finalsortedAppsByManual;
827 public List<OnboardingApp> getOnboardingApps() {
828 @SuppressWarnings("unchecked")
829 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
830 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
831 for (EPApp app : apps) {
832 OnboardingApp onboardingApp = new OnboardingApp();
833 app.setAppBasicAuthPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);//to hide password from get request
834 createOnboardingFromApp(app, onboardingApp);
835 onboardingAppsList.add(onboardingApp);
837 return onboardingAppsList;
840 @SuppressWarnings("unchecked")
842 public List<OnboardingApp> getAdminAppsOfUser(EPUser user) {
844 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
845 List<Integer> userAdminApps = new ArrayList<>();
846 final Map<String, Long> userParams = new HashMap<>();
847 userParams.put("userId", user.getId());
848 userAdminApps = dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
850 // userAdminApps.removeIf(x -> x == Integer.valueOf(ECOMP_APP_ID));
852 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size());
853 onboardingAppsList = getOnboardingApps();
855 final List<Integer> userAdminApps1 = userAdminApps;
856 List<OnboardingApp> userApplicationAdmins = onboardingAppsList.stream().filter(x -> userAdminApps1.contains((int) (long)x.getId())).collect(Collectors.toList());
858 return userApplicationAdmins;
862 public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
863 @SuppressWarnings("unchecked")
864 List<EPApp> apps = dataAccessService.getList(EPApp.class,
865 " where enabled = true and open = false and app_type!= 3 and id!=" + ECOMP_APP_ID, null, null);
867 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
868 for (EPApp app : apps) {
869 OnboardingApp onboardingApp = new OnboardingApp();
870 createOnboardingFromApp(app, onboardingApp);
871 onboardingAppsList.add(onboardingApp);
873 return onboardingAppsList;
876 @SuppressWarnings("unchecked")
877 private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
878 boolean duplicatedNameSpace = false;
879 boolean duplicatedName = false;
881 if (onboardingApp.getId() == null) {
882 List<Criterion> restrictionsList = new ArrayList<Criterion>();
883 Criterion nameCrit = Restrictions.eq("name",onboardingApp.getAppName());
884 Criterion nameSpaceCrit = null;
885 Criterion orCrit = null;
886 if (onboardingApp.getRolesInAAF()) {
887 nameSpaceCrit = Restrictions.eq("nameSpace", onboardingApp.getNameSpace());
888 orCrit = Restrictions.or(nameCrit, nameSpaceCrit);
890 orCrit = Restrictions.or(nameCrit);
891 restrictionsList.add(orCrit);
892 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
894 List<Criterion> restrictionsList = new ArrayList<Criterion>();
895 Criterion idCrit =Restrictions.eq("id", onboardingApp.getId());
896 Criterion nameCrit = Restrictions.eq("name",onboardingApp.getAppName());
897 Criterion nameSpaceCrit = null;
898 Criterion orCrit= null;
899 if (onboardingApp.getRolesInAAF()) {
900 nameSpaceCrit = Restrictions.eq("nameSpace",onboardingApp.getNameSpace());
901 orCrit = Restrictions.or(idCrit, nameSpaceCrit, nameCrit);
904 orCrit = Restrictions.or(idCrit, nameCrit);
906 restrictionsList.add(orCrit);
907 apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
910 for (EPApp app : apps) {
911 if (onboardingApp.getId() != null && onboardingApp.getId().equals(app.getId())) {
914 if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.getAppName())) {
915 duplicatedName = true;
916 if (duplicatedName) {
920 if (!duplicatedNameSpace && app.getNameSpace().equalsIgnoreCase(onboardingApp.getNameSpace())) {
921 duplicatedNameSpace = true;
922 if (duplicatedNameSpace) {
928 if (duplicatedNameSpace || duplicatedName) {
929 if (duplicatedNameSpace) {
930 fieldsValidator.addProblematicFieldName(nameSpaceField);
932 if (duplicatedName) {
933 fieldsValidator.addProblematicFieldName(nameField);
935 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
936 fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
941 public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
942 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
943 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
944 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
945 validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
947 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
948 if (modifiedOnboardingApp.getId() != null) {
949 updateApp(modifiedOnboardingApp.getId(), modifiedOnboardingApp, fieldsValidator, user);
950 logger.info(EELFLoggerDelegate.auditLogger, "Updated " + modifiedOnboardingApp.getAppName() +
951 " onboarding application details by user " + user.getLoginId());
953 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
956 return fieldsValidator;
960 public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
961 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
962 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
963 validateOnboardingApp(newOnboardingApp, fieldsValidator);
965 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
966 if (newOnboardingApp.getId() == null) {
967 updateApp(null, newOnboardingApp, fieldsValidator, user);
968 logger.info(EELFLoggerDelegate.auditLogger, "Added " + newOnboardingApp.getAppName() +
969 " Onboarding application by user " + user.getLoginId());
971 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
974 return fieldsValidator;
977 @SuppressWarnings("unchecked")
979 public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
980 FieldsValidator fieldsValidator = new FieldsValidator();
981 if (!adminRolesService.isSuperAdmin(user)) {
982 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
983 return fieldsValidator;
985 final Map<String, Long> params = new HashMap<>();
986 params.put("app_id", appid);
988 //Checking if App is associated with any exiting microservices- ep_microservice:
989 final Map<String, Long> queryparams = new HashMap<>();
990 queryparams.put("applicationId", appid);
991 List<MicroserviceData> microservicesList = dataAccessService.executeNamedQuery( "getMicroservicesByAppId", queryparams, null);
992 if(microservicesList!=null && microservicesList.size()>0) {
993 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
994 return fieldsValidator;
997 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
998 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
999 for(int i=0;i<EPUserAppRolesRequestList.size();i++)
1001 dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
1004 Session localSession = null;
1005 Transaction transaction = null;
1006 Boolean result = false;
1008 localSession = sessionFactory.openSession();
1009 transaction = localSession.beginTransaction();
1011 // 1) Remove the URL for any functional menu item associated with
1013 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
1014 // Named query is stored in EP.hbm.xml, mapped to EPApp
1015 dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
1016 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted URL for any functional menu item associated with app");
1018 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
1019 // 2)Remove any favorites associated with a menu item that is
1020 // associated with this app
1021 dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
1022 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
1024 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
1025 // 3)Remove all role, appid records from fn_menu_functional_role
1026 // that are associated with this app
1027 dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
1028 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
1030 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1031 // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
1032 // that are associated with this app
1033 dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
1034 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1036 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
1037 // 5)Remove all rolefunctions, appid records from ep_app_function
1038 // that are associated with this app
1039 dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
1040 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
1042 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
1043 // 6)Remove all records from fn_user_role associated with this app
1044 dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
1045 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
1047 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
1048 // 7)Remove any widgets associated with this app
1049 dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
1050 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
1052 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
1053 // 8)Remove any roles associated with this app
1054 dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
1055 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
1057 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
1058 // 9)Remove all records from fn_role associated with this app
1059 dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
1060 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
1062 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
1063 // 10)Remove app contact us entries
1064 dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
1065 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
1067 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
1068 // 11)Remove rows in the app personalization selection table
1069 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
1070 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
1072 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
1073 // 12)Remove rows in the app personalization sort table
1074 dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
1075 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
1077 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
1078 // 13)Remove rows in the app personalization sort table
1079 dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
1080 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
1082 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
1083 // 14)Remove rows in the ep_web_analytics_source
1084 dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
1085 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
1087 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
1088 // 15)Delete the app
1089 dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
1090 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
1093 // 1) Remove the URL for any functional menu item associated with
1095 String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
1096 + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
1098 Query query = localSession.createSQLQuery(sql);
1099 query.executeUpdate();
1101 // Remove any favorites associated with a menu item that is
1102 // associated with this app
1103 sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
1104 + " where fn_menu_functional_roles.app_id='" + appid + "' "
1105 + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
1107 query = localSession.createSQLQuery(sql);
1108 query.executeUpdate();
1110 // Remove all role, appid records from fn_menu_functional_role
1111 // that are associated with this app
1112 sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
1114 query = localSession.createSQLQuery(sql);
1115 query.executeUpdate();
1118 // Remove all roles, rolefunctions, appid records from ep_app_role_function
1119 // that are associated with this app
1120 sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
1121 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1122 query = localSession.createSQLQuery(sql);
1123 query.executeUpdate();
1125 //Remove all rolefunctions, appid records from ep_app_function
1126 // that are associated with this app
1127 sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
1128 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1129 query = localSession.createSQLQuery(sql);
1130 query.executeUpdate();
1132 // Remove all records from fn_user_role associated with this app
1133 sql = "delete from fn_user_role where app_id='" + appid + "'";
1135 query = localSession.createSQLQuery(sql);
1136 query.executeUpdate();
1138 // Remove any widgets associated with this app
1139 sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
1141 query = localSession.createSQLQuery(sql);
1142 query.executeUpdate();
1144 // Remove any roles associated with this app
1145 sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
1146 + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
1148 query = localSession.createSQLQuery(sql);
1149 query.executeUpdate();
1151 // Remove all records from fn_role associated with this app
1152 sql = "delete from fn_role where app_id='" + appid + "'";
1154 query = localSession.createSQLQuery(sql);
1155 query.executeUpdate();
1157 // Remove app contact us entries
1158 sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
1160 query = localSession.createSQLQuery(sql);
1161 query.executeUpdate();
1163 // Remove rows in the app personalization selection table
1164 sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
1166 query = localSession.createSQLQuery(sql);
1167 query.executeUpdate();
1169 // Remove rows in the app personalization sort table
1170 sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
1172 query = localSession.createSQLQuery(sql);
1173 query.executeUpdate();
1175 // Remove rows in the app personalization sort table
1176 sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
1178 query = localSession.createSQLQuery(sql);
1179 query.executeUpdate();
1181 // Remove rows in the app personalization sort table
1182 sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
1184 query = localSession.createSQLQuery(sql);
1185 query.executeUpdate();
1188 sql = "delete from fn_app where app_id='" + appid + "'";
1190 query = localSession.createSQLQuery(sql);
1191 query.executeUpdate();
1193 transaction.commit();
1196 logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
1197 } catch (Exception e) {
1198 logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
1199 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
1200 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
1202 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
1205 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1207 return fieldsValidator;
1210 private static Object syncRests = new Object();
1212 // An app has been enabled/disabled. Must enable/disable all associated
1213 // functional menu items.
1214 protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1215 String active_yn = enabled ? "Y" : "N";
1216 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1217 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1218 + " AND r.app_id = '" + appId + "' ";
1220 @SuppressWarnings("unchecked")
1221 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1222 for (FunctionalMenuItem menuItem : menuItems) {
1223 FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1225 myMenuItem.active_yn = active_yn;
1226 localSession.save(myMenuItem);
1230 // Attention! If (appId == null) we use this function to create application
1231 // otherwise we use it to modify existing application
1232 protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1233 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1234 // Separate out the code for a restricted app, since it doesn't need any
1236 if (Boolean.TRUE.equals(onboardingApp.getRestrictedApp())) {
1237 boolean result = false;
1238 Session localSession = null;
1239 Transaction transaction = null;
1241 localSession = sessionFactory.openSession();
1242 transaction = localSession.beginTransaction();
1244 if (appId == null) {
1247 app = (EPApp) localSession.get(EPApp.class, appId);
1248 if (app == null || app.getId() == null) { // App is already
1250 transaction.commit();
1251 localSession.close();
1252 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1256 createAppFromOnboarding(app, onboardingApp, localSession);
1257 localSession.saveOrUpdate(app);
1258 // Enable or disable all menu items associated with this app
1259 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1260 transaction.commit();
1262 } catch (Exception e) {
1263 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1264 EcompPortalUtils.rollbackTransaction(transaction,
1265 "updateApp rollback, exception = " + e.toString());
1267 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1270 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1274 updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1280 protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1282 synchronized (syncRests) {
1283 boolean result = false;
1284 Session localSession = null;
1285 Transaction transaction = null;
1287 localSession = sessionFactory.openSession();
1288 transaction = localSession.beginTransaction();
1290 if (appId == null) {
1293 * In the parent class, the UEB code is responsible for generating the
1294 * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1295 * may be used in future at which point we can just remove this method and
1296 * depend on parent class's method So, using UUID generator to generate the
1297 * unique key instead.
1299 String uuidStr = UUID.randomUUID().toString();
1300 String appKey = uuidStr;
1301 String appSecret = uuidStr;
1302 String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1303 onboardingApp.setUebTopicName(appMailboxName);
1304 onboardingApp.setUebKey(appKey);
1305 onboardingApp.setUebSecret(appSecret);
1307 app = (EPApp) localSession.get(EPApp.class, appId);
1308 if (app == null || app.getId() == null) {
1309 // App is already deleted!
1310 transaction.commit();
1311 localSession.close();
1312 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1316 logger.debug(EELFLoggerDelegate.debugLogger,
1317 "updateRestrictedApp: about to call createAppFromOnboarding");
1318 createAppFromOnboarding(app, onboardingApp, localSession);
1319 logger.debug(EELFLoggerDelegate.debugLogger,
1320 "updateRestrictedApp: finished calling createAppFromOnboarding");
1321 localSession.saveOrUpdate(app);
1322 logger.debug(EELFLoggerDelegate.debugLogger,
1323 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1324 // Enable or disable all menu items associated with this app
1325 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1326 logger.debug(EELFLoggerDelegate.debugLogger,
1327 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1328 transaction.commit();
1329 logger.debug(EELFLoggerDelegate.debugLogger,
1330 "updateRestrictedApp: finished calling transaction.commit");
1332 } catch (Exception e) {
1333 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1334 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1335 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1336 EcompPortalUtils.rollbackTransaction(transaction,
1337 "updateRestrictedApp rollback, exception = " + e.toString());
1339 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1342 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1349 protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1351 synchronized (syncRests) {
1352 boolean result = false;
1353 Session localSession = null;
1354 Transaction transaction = null;
1356 localSession = sessionFactory.openSession();
1357 transaction = localSession.beginTransaction();
1359 if (appId == null) {
1361 // -------------------------------------------------------------------------------------------
1362 // Register this App with the UEB communication server.
1364 // the App's unique mailbox/topic
1365 // name and keys to the FN_APP table. The App's mailbox
1367 // keys will be visible to the
1368 // admin on the ONAP portal.
1369 // -------------------------------------------------------------------------------------------
1370 TopicManager topicManager = new TopicManager() {
1372 EPAppCommonServiceImpl service;
1374 public void init(EPAppCommonServiceImpl _service) {
1378 public void createTopic(String key, String secret, String topicName,
1379 String topicDescription) throws HttpException, CambriaApiException, IOException {
1381 init(EPAppCommonServiceImpl.this);
1382 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1383 if (logger.isInfoEnabled()) {
1384 logger.info("==> createTopic");
1385 logger.info("topicName: " + topicName);
1386 logger.info("topicDescription: " + topicDescription);
1388 CambriaTopicManager tm = null;
1390 tm = service.getTopicManager(urlList, key, secret);
1391 } catch (Exception e) {
1392 logger.error("pub.build Exception ", e);
1393 throw new CambriaApiException(topicName);
1395 tm.createTopic(topicName, topicDescription, 1, 1);
1398 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1399 String topicName) throws HttpException, CambriaApiException, IOException {
1400 logger.info("==> addPublisher to topic " + topicName);
1401 final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1402 CambriaTopicManager tm = null;
1404 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1405 } catch (Exception e) {
1406 logger.error("pub.build Exception ", e);
1407 throw new CambriaApiException(topicName);
1409 tm.allowProducer(topicName, publisherKey);
1413 final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1414 .usingHosts(Helper.uebUrlList()).build();
1415 com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1416 "ONAP Portal Owner");
1417 String appKey = credential.getApiKey();
1418 String appSecret = credential.getApiSecret();
1419 String appMailboxName = null;
1421 int maxNumAttemptsToCreateATopic = 3;
1422 boolean successfullyCreatedMailbox = false;
1423 for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1424 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1427 topicManager.createTopic(
1428 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1429 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1430 appMailboxName, "ECOMP outbox for app" + onboardingApp.getAppName());
1431 successfullyCreatedMailbox = true;
1432 logger.debug(EELFLoggerDelegate.debugLogger,
1433 "Successfully created " + appMailboxName + " for App " + onboardingApp.getAppName());
1434 logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
1435 + appSecret + " generated using = " + user.getEmail());
1437 } catch (HttpException e) {
1438 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1439 if (e.getStatusCode() == 409) {
1440 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1441 + " already exists. Will try using a different name", e);
1443 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1449 if (successfullyCreatedMailbox) {
1450 onboardingApp.setUebTopicName(appMailboxName);
1451 onboardingApp.setUebKey(appKey);
1452 onboardingApp.setUebSecret(appSecret);
1456 * EP is a publisher to this App's new mailbox
1458 topicManager.addPublisher(
1459 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1460 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1461 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1465 * This App is a subscriber of its own mailbox
1467 topicManager.addSubscriber(
1468 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1469 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1473 * This App is a publisher to EP
1475 topicManager.addPublisher(
1476 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1477 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1478 PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1479 } catch (HttpException | CambriaApiException | IOException e) {
1480 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1481 logger.error(EELFLoggerDelegate.errorLogger,
1482 "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1483 transaction.commit();
1484 localSession.close();
1485 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1489 transaction.commit();
1490 localSession.close();
1491 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1495 app = (EPApp) localSession.get(EPApp.class, appId);
1496 if (app == null || app.getId() == null) {
1497 // App is already deleted!
1498 transaction.commit();
1499 localSession.close();
1500 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1504 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1505 createAppFromOnboarding(app, onboardingApp, localSession);
1506 logger.debug(EELFLoggerDelegate.debugLogger,
1507 "LR: updateApp: finished calling createAppFromOnboarding");
1508 localSession.saveOrUpdate(app);
1509 logger.debug(EELFLoggerDelegate.debugLogger,
1510 "LR: updateApp: finished calling localSession.saveOrUpdate");
1511 // Enable or disable all menu items associated with this app
1512 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1513 logger.debug(EELFLoggerDelegate.debugLogger,
1514 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1515 transaction.commit();
1516 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1517 logger.debug(EELFLoggerDelegate.debugLogger,
1518 "LR: updateApp: finished calling epUebHelper.addPublisher");
1520 } catch (Exception e) {
1521 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1522 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1523 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1524 EcompPortalUtils.rollbackTransaction(transaction,
1525 "updateApp rollback, exception = " + e.toString());
1527 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1530 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1536 public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1537 throws GeneralSecurityException, Exception {
1538 throw new Exception("This method can only be invoked from child class");
1542 * Populates a transport model of the application from a database row model.
1543 * Leaves out the thumbnail because the FE fetches images via a different
1547 * Model of database row
1548 * @param onboardingApp
1549 * Model for transport as JSON
1552 public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1553 onboardingApp.setId(app.getId());
1554 onboardingApp.setAppName(app.getName());
1555 onboardingApp.setImageUrl(app.getImageUrl());
1556 onboardingApp.setAppDescription(app.getAppDescription());
1557 onboardingApp.setAppNotes(app.getAppNotes());
1558 onboardingApp.setLandingPage(app.getLandingPage());
1559 onboardingApp.setAlternateLandingPage(app.getAlternateLandingPage());
1560 onboardingApp.setRestUrl(app.getAppRestEndpoint());
1561 onboardingApp.setIsOpen(app.getOpen());
1562 onboardingApp.setIsEnabled(app.getEnabled());
1563 onboardingApp.setAppBasicAuthUsername(app.getAppBasicAuthUsername());
1565 String effectivePwd = null;
1566 if (app.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1567 effectivePwd = EPCommonSystemProperties.APP_DISPLAY_PASSWORD;
1569 effectivePwd = decryptedPassword(app.getAppBasicAuthPassword(), app);
1571 onboardingApp.setAppBasicAuthPassword(effectivePwd);
1572 onboardingApp.setUebTopicName(app.getUebTopicName());
1573 onboardingApp.setUebKey(app.getUebKey());
1574 onboardingApp.setUebSecret(app.getUebSecret());
1575 onboardingApp.setRolesInAAF(app.getRolesInAAF());
1576 onboardingApp.setNameSpace(app.getNameSpace());
1577 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1578 onboardingApp.setModeOfIntegration(app.getModeOfIntegration());
1579 onboardingApp.setAppAck(app.getAppAck());
1580 onboardingApp.setUsesCadi(app.getUsesCadi());
1581 onboardingApp.setApplicationType(app.getAppType().toString());
1585 * Creates a database object for an application from an uploaded transport
1586 * model. Must decode the thumbnail, if any.
1589 * @param onboardingApp
1590 * @param localSession
1591 * @return The first argument.
1593 protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1594 app.setName(onboardingApp.getAppName());
1595 app.setAppDescription(onboardingApp.getAppDescription());
1596 app.setAppNotes(onboardingApp.getAppNotes());
1597 app.setLandingPage(onboardingApp.getLandingPage());
1598 app.setAlternateLandingPage(onboardingApp.getAlternateLandingPage());
1599 app.setAppRestEndpoint(onboardingApp.getRestUrl());
1600 app.setOpen(onboardingApp.getIsOpen());
1601 app.setEnabled(onboardingApp.getIsEnabled());
1602 app.setAppBasicAuthUsername(onboardingApp.getAppBasicAuthUsername());
1603 if(!onboardingApp.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1604 app.setAppBasicAuthPassword(this.encryptedPassword(onboardingApp.getAppBasicAuthPassword(), app));
1605 //app.setUebTopicName(onboardingApp.uebTopicName);
1606 app.setUebKey(onboardingApp.getUebKey());
1607 app.setUebSecret(onboardingApp.getUebSecret());
1608 app.setRolesInAAF(onboardingApp.getRolesInAAF());
1609 app.setNameSpace(onboardingApp.getNameSpace());
1610 app.setAppType(new Integer(onboardingApp.getApplicationType()));
1611 app.setModeOfIntegration(onboardingApp.getModeOfIntegration());
1612 app.setAppAck(onboardingApp.getAppAck());
1613 app.setUsesCadi(onboardingApp.getUsesCadi());
1616 if (!StringUtils.isEmpty(onboardingApp.getThumbnail())) {
1617 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1618 String[] splitBase64Thumbnail = onboardingApp.getThumbnail().split("base64,");
1619 logger.debug(EELFLoggerDelegate.debugLogger,
1620 "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1621 if (splitBase64Thumbnail.length > 1) {
1622 // This occurs when we have a new image, not an existing image
1623 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1624 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1625 // This is basically a boolean indicator that an image is
1627 app.setImageUrl(constructImageName(onboardingApp));
1628 app.setThumbnail(decodedImage);
1630 } else if (app.getThumbnail() != null && onboardingApp.getImageLink() == null) {
1631 // The thumbnail that came in from the json is empty; the previous
1632 // thumbnail is NOT empty. Must delete it.
1633 logger.debug(EELFLoggerDelegate.debugLogger,
1634 "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1635 app.setImageUrl(null);
1636 app.setThumbnail(null);
1638 logger.debug(EELFLoggerDelegate.debugLogger,
1639 "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1644 protected String constructImageName(OnboardingApp onboardingApp) {
1645 String appLandingPageURL = onboardingApp.getLandingPage();
1646 SecureRandom rand = new SecureRandom();
1647 if(appLandingPageURL == null) {
1648 appLandingPageURL = "";
1650 return "portal_" + String.valueOf(appLandingPageURL.hashCode() + "_" + rand.nextInt(100000))
1654 // Don't encrypt or decrypt the password if it is null or the empty string
1655 private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1657 if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) {
1659 result = CipherUtil.decryptPKC(encryptedAppPwd,
1660 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1661 } catch (Exception e) {
1662 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1668 protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1670 if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) {
1672 result = CipherUtil.encryptPKC(decryptedAppPwd,
1673 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1674 } catch (Exception e) {
1675 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1681 @SuppressWarnings("unchecked")
1683 public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1684 FieldsValidator fieldsValidator = new FieldsValidator();
1685 final Map<String, Long> params = new HashMap<>();
1686 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1689 params.put("userId", user.getId());
1690 epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1691 Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1692 for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1693 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1695 for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1696 if (epWidgetsManPref.getWidgetid() != null) {
1697 Long widgetid = epWidgetsManPref.getWidgetid();
1698 if (existingWidgetsIds.containsKey(widgetid)) {
1699 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1700 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1701 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1702 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1703 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1704 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1705 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1706 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1708 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1709 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1710 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1711 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1712 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1713 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1714 epWidgetsManualSort.setUserId(user.getId());
1715 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1717 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1720 } catch (Exception e) {
1721 logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1722 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1724 return fieldsValidator;
1727 @SuppressWarnings("unchecked")
1729 public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1730 FieldsValidator fieldsValidator = new FieldsValidator();
1731 final Map<String, Long> params = new HashMap<>();
1732 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1734 params.put("userId", user.getId());
1735 epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1736 Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1737 for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1738 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1740 for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1741 if (delEpWidgetsManPref.getWidgetid() != null) {
1742 Long widgetId = delEpWidgetsManPref.getWidgetid();
1743 if (existingWidgetIds.containsKey(widgetId)) {
1744 params.put("widgetId",widgetId);
1745 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1747 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1750 } catch (Exception e) {
1751 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1752 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1754 return fieldsValidator;
1758 * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1760 * @param: appsSortManual--contains User Apps Data
1762 * @param: user--contains LoggedIn User Data
1764 @SuppressWarnings("unchecked")
1766 public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1767 FieldsValidator fieldsValidator = new FieldsValidator();
1768 final Map<String, Long> params = new HashMap<>();
1769 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1772 params.put("userId", user.getId());
1773 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1774 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1775 for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1776 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1778 for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1779 if (epAppsManPref.getAppid() != null) {
1780 Long appid = epAppsManPref.getAppid();
1781 if (existingAppIds.containsKey(appid)) {
1782 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1784 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1785 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1786 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1787 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1789 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1790 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1792 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1793 epAppsManualSort.setUserId(user.getId());
1794 dataAccessService.saveDomainObject(epAppsManualSort, null);
1796 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1799 } catch (Exception e) {
1800 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1801 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1803 return fieldsValidator;
1809 * @see org.onap.portalapp.portal.service.EPAppService#
1810 * deleteUserAppSortManual(java.lang.String,
1811 * org.onap.portalapp.portal.domain.EPUser)
1813 @SuppressWarnings("unchecked")
1815 public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1816 FieldsValidator fieldsValidator = new FieldsValidator();
1817 final Map<String, Long> params = new HashMap<>();
1818 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1820 params.put("userId", user.getId());
1821 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1822 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1823 for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1824 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1826 if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1827 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1828 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1829 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1831 } catch (Exception e) {
1832 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1833 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1835 return fieldsValidator;
1838 @SuppressWarnings("unchecked")
1840 public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1841 FieldsValidator fieldsValidator = new FieldsValidator();
1842 final Map<String, Long> params = new HashMap<>();
1843 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1844 EPUserAppsSortPreference usrSortPr = null;
1846 params.put("userId", user.getId());
1847 epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1848 if (epSortTypes.size() == 0) {
1849 usrSortPr = new EPUserAppsSortPreference();
1850 usrSortPr.setUserId((int)(long)(user.getId()));
1851 usrSortPr.setSortPref(appsSortPreference.getValue());
1852 dataAccessService.saveDomainObject(usrSortPr, null);
1853 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1855 usrSortPr = epSortTypes.get(0);
1856 usrSortPr.setSortPref(appsSortPreference.getValue());
1857 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1858 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1859 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1860 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1862 } catch (Exception e) {
1863 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1864 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1866 return fieldsValidator;
1869 @SuppressWarnings("unchecked")
1871 public String getUserAppsSortTypePreference(EPUser user) {
1872 final Map<String, Long> params = new HashMap<>();
1873 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1875 params.put("userId", user.getId());
1876 userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1877 if (userSortPrefs.size() > 0)
1878 return userSortPrefs.get(0).getSortPref();
1881 } catch (Exception e) {
1882 logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1889 public List<EPApp> getUserRemoteApps(String id) {
1890 throw new RuntimeException(" Cannot be called from parent class");
1894 public UserRoles getUserProfileForLeftMenu(String loginId) {
1895 final Map<String, String> params = new HashMap<>();
1896 params.put("org_user_id", loginId);
1897 @SuppressWarnings("unchecked")
1898 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1899 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1900 if (usersRolesList == null || usersRolesList.size() < 1)
1903 return usersRolesList.get(0);
1908 public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1909 final Map<String, String> params = new HashMap<>();
1910 params.put("org_user_id", loginId);
1911 @SuppressWarnings("unchecked")
1912 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1913 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1914 if (usersRolesList == null || usersRolesList.size() < 1)
1917 return usersRolesList.get(0);
1921 public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1923 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1924 // If no roles are defined, treat this user as a guest.
1925 if (user.isGuest() || userAndRoles == null) {
1926 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1928 userAndRoles = createUserRoles(user);
1931 return userAndRoles;
1935 public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1937 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1938 // If no roles are defined, treat this user as a guest.
1939 if (user.isGuest() || userAndRoles == null) {
1940 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1942 userAndRoles = createUserRoles(user);
1945 return userAndRoles;
1949 public UserRoles createUserRoles(EPUser user)
1951 UserRole userRole = new UserRole();
1952 userRole.setUser_Id(user.getId());
1953 userRole.setOrgUserId(user.getLoginId());
1954 userRole.setFirstName(user.getFirstName());
1955 userRole.setLastName(user.getLastName());
1956 userRole.setRoleId(-1L);
1957 userRole.setRoleName("Guest");
1958 userRole.setUser_Id(-1L);
1959 UserRoles userAndRoles = new UserRoles(userRole);
1960 return userAndRoles;
1964 @SuppressWarnings("unused")
1966 public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception {
1967 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1968 HttpEntity<String> entity = new HttpEntity<>(headers);
1969 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace);
1970 ResponseEntity<String> response = null;
1973 String namespaceUrl = SystemProperties.
1974 getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "nss/" + namespace;
1976 response = template.exchange(namespaceUrl, HttpMethod.GET, entity, String.class);
1977 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace ,
1978 response.getStatusCode().value());
1979 if (response.getStatusCode().value() == 200) {
1980 String res = response.getBody();
1981 JSONObject jsonObj = new JSONObject(res);
1982 JSONArray namespaceArray = jsonObj.getJSONArray("ns");
1983 if(!namespaceArray.getJSONObject(0).has("admin")){
1984 logger.error(EELFLoggerDelegate.errorLogger,
1985 "No admins are available for requested namespace:" + namespace);
1986 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1987 "Portal Mechid is not an admin of" + namespace);
1990 JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin");
1991 ArrayList<String> list = new ArrayList<String>();
1992 if (namespaceAdminArray != null) {
1993 int len = namespaceAdminArray.length();
1994 for (int i = 0; i < len; i++) {
1995 list.add(namespaceAdminArray.get(i).toString());
1998 logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list);
1999 final String userName = SystemProperties
2000 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
2001 boolean idExists = list.stream().anyMatch(t -> userName.equals(t));
2003 logger.error(EELFLoggerDelegate.errorLogger,
2004 "Portal mechid is not admin of requested namespace:" + namespace);
2005 throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
2006 "Portal Mechid is not an admin of" + namespace);
2010 } catch (HttpClientErrorException e) {
2011 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
2012 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());