2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the “License”);
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.openecomp.portalapp.portal.service;
40 import java.io.IOException;
41 import java.security.GeneralSecurityException;
42 import java.util.ArrayList;
43 import java.util.Base64;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.LinkedList;
47 import java.util.List;
51 import javax.annotation.PostConstruct;
52 import javax.servlet.http.HttpServletResponse;
54 import org.apache.commons.lang.StringUtils;
55 import org.hibernate.Query;
56 import org.hibernate.Session;
57 import org.hibernate.SessionFactory;
58 import org.hibernate.Transaction;
59 import org.openecomp.portalapp.portal.domain.AdminUserApp;
60 import org.openecomp.portalapp.portal.domain.AdminUserApplications;
61 import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel;
62 import org.openecomp.portalapp.portal.domain.AppsResponse;
63 import org.openecomp.portalapp.portal.domain.EPApp;
64 import org.openecomp.portalapp.portal.domain.EPUser;
65 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest;
66 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail;
67 import org.openecomp.portalapp.portal.domain.EPUserAppsManualSortPreference;
68 import org.openecomp.portalapp.portal.domain.EPUserAppsSortPreference;
69 import org.openecomp.portalapp.portal.domain.EPWidgetsManualSortPreference;
70 import org.openecomp.portalapp.portal.domain.EcompApp;
71 import org.openecomp.portalapp.portal.domain.UserRole;
72 import org.openecomp.portalapp.portal.domain.UserRoles;
73 import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
74 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
75 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
76 import org.openecomp.portalapp.portal.transport.EPAppsManualPreference;
77 import org.openecomp.portalapp.portal.transport.EPAppsSortPreference;
78 import org.openecomp.portalapp.portal.transport.EPDeleteAppsManualSortPref;
79 import org.openecomp.portalapp.portal.transport.EPWidgetsSortPreference;
80 import org.openecomp.portalapp.portal.transport.FieldsValidator;
81 import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
82 import org.openecomp.portalapp.portal.transport.LocalRole;
83 import org.openecomp.portalapp.portal.transport.OnboardingApp;
84 import org.openecomp.portalapp.portal.ueb.EPUebHelper;
85 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
86 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
87 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
88 import org.openecomp.portalsdk.core.onboarding.ueb.Helper;
89 import org.openecomp.portalsdk.core.onboarding.ueb.TopicManager;
90 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
91 import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
92 import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
93 import org.openecomp.portalsdk.core.service.DataAccessService;
94 import org.openecomp.portalsdk.core.util.SystemProperties;
95 import org.springframework.beans.factory.annotation.Autowired;
97 import com.att.nsa.apiClient.http.HttpException;
98 import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
99 import com.att.nsa.cambria.client.CambriaClientBuilders;
100 import com.att.nsa.cambria.client.CambriaIdentityManager;
101 import com.att.nsa.cambria.client.CambriaTopicManager;
102 import com.google.common.primitives.Ints;
104 public class EPAppCommonServiceImpl implements EPAppService {
106 protected String ECOMP_APP_ID = "1";
107 protected String SUPER_ADMIN_ROLE_ID = "1";
108 protected String ACCOUNT_ADMIN_ROLE_ID = "999";
109 protected String RESTRICTED_APP_ROLE_ID = "900";
111 private static final String urlField = "url";
112 private static final String nameField = "name";
114 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
117 private AdminRolesService adminRolesService;
119 protected SessionFactory sessionFactory;
121 private DataAccessService dataAccessService;
123 private EPUebHelper epUebHelper;
126 private void init() {
127 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
128 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
129 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
130 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
134 public List<EPApp> getUserAsAdminApps(EPUser user) {
135 if (adminRolesService.isAccountAdmin(user)) {
136 String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
137 + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
138 + " AND FN_APP.ENABLED = 'Y'";
141 @SuppressWarnings("unchecked")
142 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
144 } catch (Exception e) {
145 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
149 logger.error(EELFLoggerDelegate.errorLogger,
150 "getUserAsAdminApps: only Account Admin may invoke this function!");
151 return new ArrayList<EPApp>();
156 public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
157 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
158 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
159 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
160 + " AND FN_APP.ENABLED = 'Y'";
162 String sql = String.format(format, orgUserId);
166 @SuppressWarnings("unchecked")
167 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
169 } catch (Exception e) {
170 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
176 public List<EPApp> getAppsFullList() {
177 @SuppressWarnings("unchecked")
178 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
183 public List<EcompApp> getEcompAppAppsFullList() {
184 return transformAppsToEcompApps(getAppsFullList());
188 public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
189 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
190 for (EPApp app : appsList) {
191 EcompApp ecompApp = new EcompApp();
192 ecompApp.setId(app.getId());
193 ecompApp.setName(app.getName());
194 ecompApp.setImageUrl(app.getImageUrl());
195 ecompApp.setDescription(app.getDescription());
196 ecompApp.setNotes(app.getNotes());
197 ecompApp.setUrl(app.getUrl());
198 ecompApp.setAlternateUrl(app.getAlternateUrl());
199 ecompApp.setUebTopicName(app.getUebTopicName());
200 ecompApp.setUebKey(app.getUebKey());
201 ecompApp.setUebSecret(app.getUebSecret());
202 ecompApp.setEnabled(app.getEnabled());
203 ecompApp.setCentralAuth(app.getCentralAuth());
204 ecompApp.setNameSpace(app.getNameSpace());
205 ecompApp.setRestrictedApp(app.isRestrictedApp());
206 ecompAppList.add(ecompApp);
212 public EPApp getApp(Long appId) {
214 @SuppressWarnings("unchecked")
215 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id = " + appId, null, null);
216 return (apps.size() > 0) ? apps.get(0) : null;
217 } catch (Exception e) {
218 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
223 @SuppressWarnings("unchecked")
225 public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
226 if (adminRolesService.isAccountAdmin(user)) {
227 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 "
228 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
229 + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
230 String sql = String.format(format, user.getId());
231 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
232 // app.APP_REST_ENDPOINT <> ''";
235 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
236 } catch (Exception e) {
237 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
238 logger.error(EELFLoggerDelegate.errorLogger,
239 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
242 return new ArrayList<AppIdAndNameTransportModel>();
246 public EPApp getAppDetail(String appName) {
247 final Map<String, String> params = new HashMap<String, String>();
249 params.put("appName", appName);
250 @SuppressWarnings("unchecked")
251 List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
252 return (apps.size() > 0) ? apps.get(0) : null;
253 } catch (Exception e) {
254 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
259 @SuppressWarnings("unchecked")
261 public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
262 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
265 if (adminRolesService.isSuperAdmin(user)) {
266 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
267 + "where app.ENABLED = 'Y' AND app.app_type = 1";
269 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 "
270 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
271 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
273 sql = String.format(format, user.getId());
274 // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
275 // app.APP_REST_ENDPOINT <> ''";
278 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
279 } catch (Exception e) {
280 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
281 logger.error(EELFLoggerDelegate.errorLogger,
282 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
285 return new ArrayList<AppIdAndNameTransportModel>();
288 protected void logQuery(String sql) {
289 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
292 public DataAccessService getDataAccessService() {
293 return dataAccessService;
296 public void setDataAccessService(DataAccessService dataAccessService) {
297 this.dataAccessService = dataAccessService;
300 @SuppressWarnings("unchecked")
302 public List<AdminUserApplications> getAppsAdmins() {
304 Map<String, String> params = new HashMap<>();
305 params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
306 List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
308 return aggregateRowsResultsByUserId(adminApps);
309 } catch (Exception e) {
310 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
315 private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
316 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
317 for (AdminUserApp app : adminApps) {
318 Long userId = app.getUser_Id();
319 if (adminUserApplications.get(userId) == null)
320 adminUserApplications.put(userId, new AdminUserApplications(app));
322 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
324 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
328 public List<AppsResponse> getAllApps(Boolean all) {
329 // If all is true, return both active and inactive apps. Otherwise, just
331 @SuppressWarnings("unchecked")
332 // Sort the list by application name so the drop-down looks pretty.
333 List<EPApp> apps = all
334 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
335 : (List<EPApp>) dataAccessService.getList(EPApp.class,
336 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
338 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
339 for (EPApp app : apps) {
340 appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
346 public UserRoles getUserProfile(String loginId) {
347 final Map<String, String> params = new HashMap<>();
348 params.put("org_user_id", loginId);
349 @SuppressWarnings("unchecked")
350 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
351 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
352 if (usersRolesList == null || usersRolesList.size() < 1)
355 return usersRolesList.get(0);
359 public UserRoles getUserProfileNormalized(EPUser user) {
361 UserRoles userAndRoles = getUserProfile(user.getLoginId());
362 // If no roles are defined, treat this user as a guest.
363 if (user.isGuest() || userAndRoles == null) {
364 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
366 UserRole userRole = new UserRole();
367 userRole.setUser_Id(user.getId());
368 userRole.setOrgUserId(user.getLoginId());
369 userRole.setFirstName(user.getFirstName());
370 userRole.setLastName(user.getLastName());
371 userRole.setRoleId(-1L);
372 userRole.setRoleName("Guest");
373 userRole.setUser_Id(-1L);
374 userAndRoles = new UserRoles(userRole);
380 protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
381 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
382 for (UserRole user : userRoleList) {
383 String orgUserId = user.getOrgUserId();
384 if (userRoles.get(orgUserId) == null)
385 userRoles.put(orgUserId, new UserRoles(user));
387 userRoles.get(orgUserId).addRole(user.getRoleName());
389 return new ArrayList<UserRoles>(userRoles.values());
392 private boolean isRestrictedApp(Long appId) {
393 EPApp app = getApp(appId);
394 return app.isRestrictedApp();
397 // For the functional menu edit
399 public List<LocalRole> getAppRoles(Long appId) {
401 if (isRestrictedApp(appId)) {
402 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
403 }else if(appId == 1){
404 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
406 sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
409 @SuppressWarnings("unchecked")
410 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
414 protected String userAppsQuery(EPUser user) {
415 StringBuilder query = new StringBuilder();
416 if (adminRolesService.isSuperAdmin(user)) {
417 query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
419 query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
421 "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
422 query.append(" AND FN_APP.ENABLED = 'Y'");
424 return query.toString();
427 protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
428 FieldsValidator fieldsValidator = new FieldsValidator();
429 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
430 || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
431 || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
432 || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID))
433 // For a normal app (appType==1), these fields must be filled
435 // For a restricted app (appType==2), they will be empty.
436 || ((!onboardingApp.restrictedApp)
437 && (onboardingApp.username == null || onboardingApp.username.length() == 0
438 || onboardingApp.appPassword == null || onboardingApp.appPassword.length() == 0))) {
439 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
441 return fieldsValidator;
445 public List<EPApp> getUserApps(EPUser user) {
446 List<EPApp> openApps = getOpenApps();
448 if (user.isGuest()) {
451 String sql = userAppsQuery(user);
454 // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
455 List<EPApp> appsList = new ArrayList<>();
456 @SuppressWarnings("unchecked")
457 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
458 HashSet<EPApp> appSet = new HashSet<>();
459 for (EPApp app : adminApps) {
464 for (EPApp app : openApps) {
465 if (!appSet.contains(app))
474 public List<EPApp> getPersAdminApps(EPUser user) {
475 final Map<String, Long> params = new HashMap<>();
476 params.put("userId", user.getId());
477 // Named query is stored in EP.hbm.xml, mapped to EPApp
478 @SuppressWarnings("unchecked")
479 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
484 public List<EPApp> getPersUserApps(EPUser user) {
485 final Map<String, Long> params = new HashMap<>();
486 params.put("userId", user.getId());
487 // Named query is stored in EP.hbm.xml, mapped to EPApp
488 @SuppressWarnings("unchecked")
489 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
497 * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog(
498 * org.openecomp.portalapp.portal.domain.EPUser)
501 public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
502 final Map<String, Long> params = new HashMap<>();
503 params.put("userId", user.getId());
504 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
505 @SuppressWarnings("unchecked")
506 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
514 * org.openecomp.portalapp.portal.service.EPAppService#getAdminAppCatalog(
515 * org.openecomp.portalapp.portal.domain.EPUser)
518 public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
519 final Map<String, Long> params = new HashMap<>();
520 params.put("userId", user.getId());
521 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
522 @SuppressWarnings("unchecked")
523 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
527 private List<EPApp> getOpenApps() {
528 @SuppressWarnings("unchecked")
529 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
533 @SuppressWarnings("unchecked")
535 public List<EPApp> getAppsOrderByName(EPUser user) {
536 final Map<String, Long> params = new HashMap<>();
537 List<EPApp> sortedAppsByName = null;
539 if (adminRolesService.isSuperAdmin(user)) {
540 params.put("userId", user.getId());
541 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
543 params.put("userId", user.getId());
544 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
546 } catch (Exception e) {
547 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
549 return sortedAppsByName;
552 @SuppressWarnings("unchecked")
554 public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
556 final Map<String, Long> params = new HashMap<>();
557 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
558 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
560 if (adminRolesService.isSuperAdmin(user)) {
561 params.put("userId", user.getId());
562 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
564 params.put("userId", user.getId());
565 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
567 Set<String> epAppSet = new HashSet<String>();
568 for (EPApp eapp : sortedAppsByLastUsed)
569 if (!epAppSet.contains(eapp.getName())) {
570 finalsortedAppsByLastUsed.add(eapp);
571 epAppSet.add(eapp.getName());
574 } catch (Exception e) {
575 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
577 return finalsortedAppsByLastUsed;
580 @SuppressWarnings("unchecked")
582 public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
583 final Map<String, Long> params = new HashMap<>();
584 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
585 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
587 if (adminRolesService.isSuperAdmin(user)) {
588 params.put("userId", user.getId());
589 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
591 params.put("userId", user.getId());
592 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
594 Set<String> epAppSet = new HashSet<String>();
596 for (EPApp eapp : sortedAppsByMostUsed) {
597 if (!epAppSet.contains(eapp.getName())) {
598 finalsortedAppsByMostUsed.add(eapp);
599 epAppSet.add(eapp.getName());
602 } catch (Exception e) {
603 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
606 return finalsortedAppsByMostUsed;
610 * This Method retrieves the User Apps by Sort Manual Preference
612 * @param: user--contains LoggedIn User Data
614 @SuppressWarnings("unchecked")
616 public List<EPApp> getAppsOrderByManual(EPUser user) {
617 final Map<String, Long> params = new HashMap<>();
618 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
619 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
621 if (adminRolesService.isSuperAdmin(user)) {
622 params.put("userId", user.getId());
623 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
625 params.put("userId", user.getId());
626 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
628 Set<String> epAppSet = new HashSet<String>();
630 for (EPApp eapp : sortedAppsByManual) {
631 if (!epAppSet.contains(eapp.getName())) {
632 finalsortedAppsByManual.add(eapp);
633 epAppSet.add(eapp.getName());
636 } catch (Exception e) {
637 logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
639 return finalsortedAppsByManual;
643 public List<OnboardingApp> getOnboardingApps() {
644 @SuppressWarnings("unchecked")
645 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
646 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
647 for (EPApp app : apps) {
648 OnboardingApp onboardingApp = new OnboardingApp();
649 createOnboardingFromApp(app, onboardingApp);
650 onboardingAppsList.add(onboardingApp);
652 return onboardingAppsList;
656 public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
657 @SuppressWarnings("unchecked")
658 List<EPApp> apps = dataAccessService.getList(EPApp.class,
659 " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
660 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
661 for (EPApp app : apps) {
662 OnboardingApp onboardingApp = new OnboardingApp();
663 createOnboardingFromApp(app, onboardingApp);
664 onboardingAppsList.add(onboardingApp);
666 return onboardingAppsList;
669 @SuppressWarnings("unchecked")
670 private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
671 boolean duplicatedUrl = false;
672 boolean duplicatedName = false;
674 if (onboardingApp.id == null) {
675 apps = dataAccessService.getList(EPApp.class,
676 " where url = '" + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null);
678 apps = dataAccessService.getList(EPApp.class, " where id = " + onboardingApp.id + " or url = '"
679 + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null);
681 for (EPApp app : apps) {
682 if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) {
685 if (!duplicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) {
686 duplicatedUrl = true;
687 if (duplicatedName) {
691 if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
692 duplicatedName = true;
698 if (duplicatedUrl || duplicatedName) {
700 fieldsValidator.addProblematicFieldName(urlField);
702 if (duplicatedName) {
703 fieldsValidator.addProblematicFieldName(nameField);
705 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
706 fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
711 public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
712 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
713 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
714 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
715 validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
717 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
718 if (modifiedOnboardingApp.id != null) {
719 updateApp(modifiedOnboardingApp.id, modifiedOnboardingApp, fieldsValidator, user);
721 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
724 return fieldsValidator;
728 public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
729 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
730 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
731 validateOnboardingApp(newOnboardingApp, fieldsValidator);
733 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
734 if (newOnboardingApp.id == null) {
735 updateApp(null, newOnboardingApp, fieldsValidator, user);
737 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
740 return fieldsValidator;
743 @SuppressWarnings("unchecked")
745 public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
746 FieldsValidator fieldsValidator = new FieldsValidator();
747 if (!adminRolesService.isSuperAdmin(user)) {
748 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
749 return fieldsValidator;
751 final Map<String, Long> params = new HashMap<>();
752 params.put("app_id", appid);
753 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
754 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
755 for(int i=0;i<EPUserAppRolesRequestList.size();i++)
757 dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
761 Boolean result = false;
762 Session localSession = null;
763 Transaction transaction = null;
765 localSession = sessionFactory.openSession();
766 transaction = localSession.beginTransaction();
768 // 1) Remove the URL for any functional menu item associated with
770 String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
771 + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
773 Query query = localSession.createSQLQuery(sql);
774 query.executeUpdate();
776 // Remove any favorites associated with a menu item that is
777 // associated with this app
778 sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
779 + " where fn_menu_functional_roles.app_id='" + appid + "' "
780 + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
782 query = localSession.createSQLQuery(sql);
783 query.executeUpdate();
785 // Remove all role, appid records from fn_menu_functional_role
786 // that are associated with this app
787 sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
789 query = localSession.createSQLQuery(sql);
790 query.executeUpdate();
793 // Remove all roles, rolefunctions, appid records from ep_app_role_function
794 // that are associated with this app
795 sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
796 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
797 query = localSession.createSQLQuery(sql);
798 query.executeUpdate();
800 //Remove all rolefunctions, appid records from ep_app_function
801 // that are associated with this app
802 sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
803 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
804 query = localSession.createSQLQuery(sql);
805 query.executeUpdate();
807 // Remove all records from fn_user_role associated with this app
808 sql = "delete from fn_user_role where app_id='" + appid + "'";
810 query = localSession.createSQLQuery(sql);
811 query.executeUpdate();
813 // Remove any widgets associated with this app
814 sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
816 query = localSession.createSQLQuery(sql);
817 query.executeUpdate();
819 // Remove any roles associated with this app
820 sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
821 + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
823 query = localSession.createSQLQuery(sql);
824 query.executeUpdate();
826 // Remove all records from fn_role associated with this app
827 sql = "delete from fn_role where app_id='" + appid + "'";
829 query = localSession.createSQLQuery(sql);
830 query.executeUpdate();
832 // Remove app contact us entries
833 sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
835 query = localSession.createSQLQuery(sql);
836 query.executeUpdate();
838 // Remove rows in the app personalization selection table
839 sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
841 query = localSession.createSQLQuery(sql);
842 query.executeUpdate();
844 // Remove rows in the app personalization sort table
845 sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
847 query = localSession.createSQLQuery(sql);
848 query.executeUpdate();
850 // Remove rows in the app personalization sort table
851 sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
853 query = localSession.createSQLQuery(sql);
854 query.executeUpdate();
856 // Remove rows in the app personalization sort table
857 sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
859 query = localSession.createSQLQuery(sql);
860 query.executeUpdate();
863 sql = "delete from fn_app where app_id='" + appid + "'";
865 query = localSession.createSQLQuery(sql);
866 query.executeUpdate();
868 transaction.commit();
870 } catch (Exception e) {
871 logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
872 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
873 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
875 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
878 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
880 return fieldsValidator;
883 private static Object syncRests = new Object();
885 // An app has been enabled/disabled. Must enable/disable all associated
886 // functional menu items.
887 protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
888 String active_yn = enabled ? "Y" : "N";
889 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
890 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
891 + " AND r.app_id = '" + appId + "' ";
893 @SuppressWarnings("unchecked")
894 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
895 for (FunctionalMenuItem menuItem : menuItems) {
896 FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
898 myMenuItem.active_yn = active_yn;
899 localSession.save(myMenuItem);
903 // Attention! If (appId == null) we use this function to create application
904 // otherwise we use it to modify existing application
905 protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
906 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
907 // Separate out the code for a restricted app, since it doesn't need any
909 if (onboardingApp.restrictedApp) {
910 boolean result = false;
911 Session localSession = null;
912 Transaction transaction = null;
914 localSession = sessionFactory.openSession();
915 transaction = localSession.beginTransaction();
920 app = (EPApp) localSession.get(EPApp.class, appId);
921 if (app == null || app.getId() == null) { // App is already
923 transaction.commit();
924 localSession.close();
925 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
929 createAppFromOnboarding(app, onboardingApp, localSession);
930 localSession.saveOrUpdate(app);
931 // Enable or disable all menu items associated with this app
932 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
933 transaction.commit();
935 } catch (Exception e) {
936 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
937 EcompPortalUtils.rollbackTransaction(transaction,
938 "updateApp rollback, exception = " + e.toString());
940 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
943 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
947 updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
952 protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
954 synchronized (syncRests) {
955 boolean result = false;
956 Session localSession = null;
957 Transaction transaction = null;
959 localSession = sessionFactory.openSession();
960 transaction = localSession.beginTransaction();
964 // -------------------------------------------------------------------------------------------
965 // Register this App with the UEB communication server.
967 // the App's unique mailbox/topic
968 // name and keys to the FN_APP table. The App's mailbox
970 // keys will be visible to the
971 // admin on the ECOMP portal.
972 // -------------------------------------------------------------------------------------------
973 TopicManager topicManager = new TopicManager() {
975 EPAppCommonServiceImpl service;
977 public void init(EPAppCommonServiceImpl _service) {
981 public void createTopic(String key, String secret, String topicName,
982 String topicDescription) throws HttpException, CambriaApiException, IOException {
984 init(EPAppCommonServiceImpl.this);
985 final LinkedList<String> urlList = Helper.uebUrlList();
986 if (logger.isInfoEnabled()) {
987 logger.info("==> createTopic");
988 logger.info("topicName: " + topicName);
989 logger.info("topicDescription: " + topicDescription);
991 CambriaTopicManager tm = null;
993 tm = service.getTopicManager(urlList, key, secret);
994 } catch (Exception e) {
995 logger.error("pub.build Exception ", e);
996 throw new CambriaApiException(topicName);
998 tm.createTopic(topicName, topicDescription, 1, 1);
1001 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1002 String topicName) throws HttpException, CambriaApiException, IOException {
1003 logger.info("==> addPublisher to topic " + topicName);
1004 final LinkedList<String> urlList = Helper.uebUrlList();
1005 CambriaTopicManager tm = null;
1007 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1008 } catch (Exception e) {
1009 logger.error("pub.build Exception ", e);
1010 throw new CambriaApiException(topicName);
1012 tm.allowProducer(topicName, publisherKey);
1016 final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1017 .usingHosts(Helper.uebUrlList()).build();
1018 com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1019 "ECOMP Portal Owner");
1020 String appKey = credential.getApiKey();
1021 String appSecret = credential.getApiSecret();
1022 String appMailboxName = null;
1024 int maxNumAttemptsToCreateATopic = 3;
1025 boolean successfullyCreatedMailbox = false;
1026 for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1027 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1030 topicManager.createTopic(
1031 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1032 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1033 appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
1034 successfullyCreatedMailbox = true;
1035 logger.debug(EELFLoggerDelegate.debugLogger,
1036 "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
1037 logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
1038 + appSecret + " generated using = " + user.getEmail());
1040 } catch (HttpException e) {
1041 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1042 if (e.getStatusCode() == 409) {
1043 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1044 + " already exists. Will try using a different name", e);
1046 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1052 if (successfullyCreatedMailbox) {
1053 onboardingApp.setUebTopicName(appMailboxName);
1054 onboardingApp.setUebKey(appKey);
1055 onboardingApp.setUebSecret(appSecret);
1059 * EP is a publisher to this App's new mailbox
1061 topicManager.addPublisher(
1062 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1063 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1064 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1068 * This App is a subscriber of its own mailbox
1070 topicManager.addSubscriber(
1071 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1072 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1076 * This App is a publisher to EP
1078 topicManager.addPublisher(
1079 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1080 PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1081 PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1082 } catch (HttpException | CambriaApiException | IOException e) {
1083 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1084 logger.error(EELFLoggerDelegate.errorLogger,
1085 "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1086 transaction.commit();
1087 localSession.close();
1088 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1092 transaction.commit();
1093 localSession.close();
1094 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1098 app = (EPApp) localSession.get(EPApp.class, appId);
1099 if (app == null || app.getId() == null) {
1100 // App is already deleted!
1101 transaction.commit();
1102 localSession.close();
1103 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1107 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1108 createAppFromOnboarding(app, onboardingApp, localSession);
1109 logger.debug(EELFLoggerDelegate.debugLogger,
1110 "LR: updateApp: finished calling createAppFromOnboarding");
1111 localSession.saveOrUpdate(app);
1112 logger.debug(EELFLoggerDelegate.debugLogger,
1113 "LR: updateApp: finished calling localSession.saveOrUpdate");
1114 // Enable or disable all menu items associated with this app
1115 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1116 logger.debug(EELFLoggerDelegate.debugLogger,
1117 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1118 transaction.commit();
1119 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1120 epUebHelper.addPublisher(app);
1121 logger.debug(EELFLoggerDelegate.debugLogger,
1122 "LR: updateApp: finished calling epUebHelper.addPublisher");
1124 } catch (Exception e) {
1125 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1126 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1127 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1128 EcompPortalUtils.rollbackTransaction(transaction,
1129 "updateApp rollback, exception = " + e.toString());
1131 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1134 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1140 public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1141 throws GeneralSecurityException, Exception {
1142 throw new Exception("This method can only be invoked from child class");
1146 * Populates a transport model of the application from a database row model.
1147 * Leaves out the thumbnail because the FE fetches images via a different
1151 * Model of database row
1152 * @param onboardingApp
1153 * Model for transport as JSON
1156 public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1157 onboardingApp.id = app.getId();
1158 onboardingApp.name = app.getName();
1159 onboardingApp.imageUrl = app.getImageUrl();
1160 onboardingApp.description = app.getDescription();
1161 onboardingApp.notes = app.getNotes();
1162 onboardingApp.url = app.getUrl();
1163 onboardingApp.alternateUrl = app.getAlternateUrl();
1164 onboardingApp.restUrl = app.getAppRestEndpoint();
1165 onboardingApp.isOpen = app.getOpen();
1166 onboardingApp.isEnabled = app.getEnabled();
1167 onboardingApp.username = app.getUsername();
1168 onboardingApp.appPassword = decryptedPassword(app.getAppPassword(), app);
1169 onboardingApp.uebTopicName = app.getUebTopicName();
1170 onboardingApp.uebKey = app.getUebKey();
1171 onboardingApp.uebSecret = app.getUebSecret();
1172 onboardingApp.isCentralAuth = app.getCentralAuth();
1173 onboardingApp.nameSpace = app.getNameSpace();
1174 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1175 // if (app.getThumbnail() != null)
1176 // onboardingApp.thumbnail = new
1177 // String(Base64.getEncoder().encode(app.getThumbnail()));
1181 * Creates a database object for an application from an uploaded transport
1182 * model. Must decode the thumbnail, if any.
1185 * @param onboardingApp
1186 * @param localSession
1187 * @return The first argument.
1189 protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1190 app.setName(onboardingApp.name);
1191 app.setDescription(onboardingApp.description);
1192 app.setNotes(onboardingApp.notes);
1193 app.setUrl(onboardingApp.url);
1194 app.setAlternateUrl(onboardingApp.alternateUrl);
1195 app.setAppRestEndpoint(onboardingApp.restUrl);
1196 app.setOpen(onboardingApp.isOpen);
1197 app.setEnabled(onboardingApp.isEnabled);
1198 app.setUsername(onboardingApp.username);
1199 app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
1200 app.setUebTopicName(onboardingApp.uebTopicName);
1201 app.setUebKey(onboardingApp.uebKey);
1202 app.setUebSecret(onboardingApp.uebSecret);
1203 app.setCentralAuth(onboardingApp.isCentralAuth);
1204 app.setNameSpace(onboardingApp.nameSpace);
1205 app.setRestrictedApp(onboardingApp.restrictedApp);
1206 if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
1207 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1208 String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
1209 logger.debug(EELFLoggerDelegate.debugLogger,
1210 "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1211 if (splitBase64Thumbnail.length > 1) {
1212 // This occurs when we have a new image, not an existing image
1213 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1214 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1215 // This is basically a boolean indicator that an image is
1217 app.setImageUrl(constructImageName(onboardingApp));
1218 app.setThumbnail(decodedImage);
1220 } else if (app.getThumbnail() != null && onboardingApp.imageLink == null) {
1221 // The thumbnail that came in from the json is empty; the previous
1222 // thumbnail is NOT empty. Must delete it.
1223 logger.debug(EELFLoggerDelegate.debugLogger,
1224 "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1225 app.setImageUrl(null);
1226 app.setThumbnail(null);
1228 logger.debug(EELFLoggerDelegate.debugLogger,
1229 "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1234 protected String constructImageName(OnboardingApp onboardingApp) {
1235 return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
1239 // Don't encrypt or decrypt the password if it is null or the empty string
1240 private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1242 if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) {
1244 result = CipherUtil.decrypt(encryptedAppPwd,
1245 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1246 } catch (Exception e) {
1247 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1253 protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1255 if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) {
1257 result = CipherUtil.encrypt(decryptedAppPwd,
1258 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1259 } catch (Exception e) {
1260 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1266 @SuppressWarnings("unchecked")
1268 public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1269 FieldsValidator fieldsValidator = new FieldsValidator();
1270 final Map<String, Long> params = new HashMap<>();
1271 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1274 params.put("userId", user.getId());
1275 epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1276 Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1277 for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1278 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1280 for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1281 if (epWidgetsManPref.getWidgetid() != null) {
1282 Long widgetid = epWidgetsManPref.getWidgetid();
1283 if (existingWidgetsIds.containsKey(widgetid)) {
1284 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1285 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1286 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1287 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1288 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1289 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1290 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1291 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1293 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1294 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1295 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1296 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1297 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1298 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1299 epWidgetsManualSort.setUserId(Ints.checkedCast(user.getId()));
1300 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1302 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1305 } catch (Exception e) {
1306 logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1307 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1309 return fieldsValidator;
1312 @SuppressWarnings("unchecked")
1314 public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1315 FieldsValidator fieldsValidator = new FieldsValidator();
1316 final Map<String, Long> params = new HashMap<>();
1317 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1319 params.put("userId", user.getId());
1320 epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1321 Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1322 for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1323 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1325 for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1326 if (delEpWidgetsManPref.getWidgetid() != null) {
1327 Long widgetId = delEpWidgetsManPref.getWidgetid();
1328 if (existingWidgetIds.containsKey(widgetId)) {
1329 dataAccessService.deleteDomainObjects(EPWidgetsManualSortPreference.class,
1330 "widget_id=" + widgetId + " AND user_id=" + user.getId(), null);
1332 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1335 } catch (Exception e) {
1336 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1337 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1339 return fieldsValidator;
1343 * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1345 * @param: appsSortManual--contains User Apps Data
1347 * @param: user--contains LoggedIn User Data
1349 @SuppressWarnings("unchecked")
1351 public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1352 FieldsValidator fieldsValidator = new FieldsValidator();
1353 final Map<String, Long> params = new HashMap<>();
1354 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1357 params.put("userId", user.getId());
1358 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1359 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1360 for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1361 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1363 for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1364 if (epAppsManPref.getAppid() != null) {
1365 Long appid = epAppsManPref.getAppid();
1366 if (existingAppIds.containsKey(appid)) {
1367 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1369 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1370 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1371 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1372 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1374 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1375 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1377 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1378 epAppsManualSort.setUserId(Ints.checkedCast(user.getId()));
1379 dataAccessService.saveDomainObject(epAppsManualSort, null);
1381 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1384 } catch (Exception e) {
1385 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1386 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1388 return fieldsValidator;
1394 * @see org.openecomp.portalapp.portal.service.EPAppService#
1395 * deleteUserAppSortManual(java.lang.String,
1396 * org.openecomp.portalapp.portal.domain.EPUser)
1398 @SuppressWarnings("unchecked")
1400 public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1401 FieldsValidator fieldsValidator = new FieldsValidator();
1402 final Map<String, Long> params = new HashMap<>();
1403 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1405 params.put("userId", user.getId());
1406 epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1407 Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1408 for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1409 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1411 if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1412 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1413 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1414 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1416 } catch (Exception e) {
1417 logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1418 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1420 return fieldsValidator;
1423 @SuppressWarnings("unchecked")
1425 public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1426 FieldsValidator fieldsValidator = new FieldsValidator();
1427 final Map<String, Long> params = new HashMap<>();
1428 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1429 EPUserAppsSortPreference usrSortPr = null;
1431 params.put("userId", user.getId());
1432 epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1433 if (epSortTypes.size() == 0) {
1434 usrSortPr = new EPUserAppsSortPreference();
1435 usrSortPr.setUserId(Ints.checkedCast(user.getId()));
1436 usrSortPr.setSortPref(appsSortPreference.getValue());
1437 dataAccessService.saveDomainObject(usrSortPr, null);
1438 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1440 usrSortPr = epSortTypes.get(0);
1441 usrSortPr.setSortPref(appsSortPreference.getValue());
1442 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1443 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1444 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1445 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1447 } catch (Exception e) {
1448 logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1449 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1451 return fieldsValidator;
1454 @SuppressWarnings("unchecked")
1456 public String getUserAppsSortTypePreference(EPUser user) {
1457 final Map<String, Long> params = new HashMap<>();
1458 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1460 params.put("userId", user.getId());
1461 userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1462 if (userSortPrefs.size() > 0)
1463 return userSortPrefs.get(0).getSortPref();
1466 } catch (Exception e) {
1467 logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1474 public List<EPApp> getUserRemoteApps(String id) {
1475 throw new RuntimeException(" Cannot be called from parent class");
1479 public UserRoles getUserProfileForLeftMenu(String loginId) {
1480 final Map<String, String> params = new HashMap<>();
1481 params.put("org_user_id", loginId);
1482 @SuppressWarnings("unchecked")
1483 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1484 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1485 if (usersRolesList == null || usersRolesList.size() < 1)
1488 return usersRolesList.get(0);
1493 public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1495 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1496 // If no roles are defined, treat this user as a guest.
1497 if (user.isGuest() || userAndRoles == null) {
1498 logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1500 UserRole userRole = new UserRole();
1501 userRole.setUser_Id(user.getId());
1502 userRole.setOrgUserId(user.getLoginId());
1503 userRole.setFirstName(user.getFirstName());
1504 userRole.setLastName(user.getLastName());
1505 userRole.setRoleId(-1L);
1506 userRole.setRoleName("Guest");
1507 userRole.setUser_Id(-1L);
1508 userAndRoles = new UserRoles(userRole);
1511 return userAndRoles;