Deliver centralized role management feature
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / EPAppCommonServiceImpl.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.service;
21
22 import java.io.IOException;
23 import java.security.GeneralSecurityException;
24 import java.util.ArrayList;
25 import java.util.Base64;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Set;
32
33 import javax.annotation.PostConstruct;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.apache.commons.lang.StringUtils;
37 import org.hibernate.Query;
38 import org.hibernate.Session;
39 import org.hibernate.SessionFactory;
40 import org.hibernate.Transaction;
41 import org.openecomp.portalapp.portal.domain.AdminUserApp;
42 import org.openecomp.portalapp.portal.domain.AdminUserApplications;
43 import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel;
44 import org.openecomp.portalapp.portal.domain.AppsResponse;
45 import org.openecomp.portalapp.portal.domain.EPApp;
46 import org.openecomp.portalapp.portal.domain.EPUser;
47 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest;
48 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail;
49 import org.openecomp.portalapp.portal.domain.EPUserAppsManualSortPreference;
50 import org.openecomp.portalapp.portal.domain.EPUserAppsSortPreference;
51 import org.openecomp.portalapp.portal.domain.EPWidgetsManualSortPreference;
52 import org.openecomp.portalapp.portal.domain.EcompApp;
53 import org.openecomp.portalapp.portal.domain.UserRole;
54 import org.openecomp.portalapp.portal.domain.UserRoles;
55 import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
56 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
57 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
58 import org.openecomp.portalapp.portal.transport.EPAppsManualPreference;
59 import org.openecomp.portalapp.portal.transport.EPAppsSortPreference;
60 import org.openecomp.portalapp.portal.transport.EPDeleteAppsManualSortPref;
61 import org.openecomp.portalapp.portal.transport.EPWidgetsSortPreference;
62 import org.openecomp.portalapp.portal.transport.FieldsValidator;
63 import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
64 import org.openecomp.portalapp.portal.transport.LocalRole;
65 import org.openecomp.portalapp.portal.transport.OnboardingApp;
66 import org.openecomp.portalapp.portal.ueb.EPUebHelper;
67 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
68 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
69 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
70 import org.openecomp.portalsdk.core.onboarding.ueb.Helper;
71 import org.openecomp.portalsdk.core.onboarding.ueb.TopicManager;
72 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
73 import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
74 import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
75 import org.openecomp.portalsdk.core.service.DataAccessService;
76 import org.openecomp.portalsdk.core.util.SystemProperties;
77 import org.springframework.beans.factory.annotation.Autowired;
78
79 import com.att.nsa.apiClient.http.HttpException;
80 import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
81 import com.att.nsa.cambria.client.CambriaClientBuilders;
82 import com.att.nsa.cambria.client.CambriaIdentityManager;
83 import com.att.nsa.cambria.client.CambriaTopicManager;
84 import com.google.common.primitives.Ints;
85
86 public class EPAppCommonServiceImpl implements EPAppService {
87
88         protected String ECOMP_APP_ID = "1";
89         protected String SUPER_ADMIN_ROLE_ID = "1";
90         protected String ACCOUNT_ADMIN_ROLE_ID = "999";
91         protected String RESTRICTED_APP_ROLE_ID = "900";
92
93         private static final String urlField = "url";
94         private static final String nameField = "name";
95
96         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
97
98         @Autowired
99         private AdminRolesService adminRolesService;
100         @Autowired
101         protected SessionFactory sessionFactory;
102         @Autowired
103         private DataAccessService dataAccessService;
104         @Autowired
105         private EPUebHelper epUebHelper;
106
107         @PostConstruct
108         private void init() {
109                 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
110                 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
111                 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
112                 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
113         }
114
115         @Override
116         public List<EPApp> getUserAsAdminApps(EPUser user) {
117                 if (adminRolesService.isAccountAdmin(user)) {
118                         String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
119                                         + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
120                                         + " AND FN_APP.ENABLED = 'Y'";
121                         logQuery(sql);
122                         try {
123                                 @SuppressWarnings("unchecked")
124                                 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
125                                 return adminApps;
126                         } catch (Exception e) {
127                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
128                                 return null;
129                         }
130                 } else {
131                         logger.error(EELFLoggerDelegate.errorLogger,
132                                         "getUserAsAdminApps: only Account Admin may invoke this function!");
133                         return new ArrayList<EPApp>();
134                 }
135         }
136
137         @Override
138         public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
139                 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
140                                 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
141                                 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
142                                 + " AND FN_APP.ENABLED = 'Y'";
143
144                 String sql = String.format(format, orgUserId);
145                 logQuery(sql);
146
147                 try {
148                         @SuppressWarnings("unchecked")
149                         List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
150                         return adminApps;
151                 } catch (Exception e) {
152                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
153                         return null;
154                 }
155         }
156
157         @Override
158         public List<EPApp> getAppsFullList() {
159                 @SuppressWarnings("unchecked")
160                 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
161                 return apps;
162         }
163
164         @Override
165         public List<EcompApp> getEcompAppAppsFullList() {
166                 return transformAppsToEcompApps(getAppsFullList());
167         }
168
169         @Override
170         public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
171                 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
172                 for (EPApp app : appsList) {
173                         EcompApp ecompApp = new EcompApp();
174                         ecompApp.setId(app.getId());
175                         ecompApp.setName(app.getName());
176                         ecompApp.setImageUrl(app.getImageUrl());
177                         ecompApp.setDescription(app.getDescription());
178                         ecompApp.setNotes(app.getNotes());
179                         ecompApp.setUrl(app.getUrl());
180                         ecompApp.setAlternateUrl(app.getAlternateUrl());
181                         ecompApp.setUebTopicName(app.getUebTopicName());
182                         ecompApp.setUebKey(app.getUebKey());
183                         ecompApp.setUebSecret(app.getUebSecret());
184                         ecompApp.setEnabled(app.getEnabled());
185                         ecompApp.setCentralAuth(app.getCentralAuth());
186                         ecompApp.setNameSpace(app.getNameSpace());
187                         ecompApp.setRestrictedApp(app.isRestrictedApp());
188                         ecompAppList.add(ecompApp);
189                 }
190                 return ecompAppList;
191         }
192
193         @Override
194         public EPApp getApp(Long appId) {
195                 try {
196                         @SuppressWarnings("unchecked")
197                         List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id = " + appId, null, null);
198                         return (apps.size() > 0) ? apps.get(0) : null;
199                 } catch (Exception e) {
200                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
201                         return null;
202                 }
203         }
204
205         @SuppressWarnings("unchecked")
206         @Override
207         public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
208                 if (adminRolesService.isAccountAdmin(user)) {
209                         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 "
210                                         + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
211                                         + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
212                         String sql = String.format(format, user.getId());
213                         // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
214                         // app.APP_REST_ENDPOINT <> ''";
215                         logQuery(sql);
216                         try {
217                                 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
218                         } catch (Exception e) {
219                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
220                                 logger.error(EELFLoggerDelegate.errorLogger,
221                                                 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
222                         }
223                 }
224                 return new ArrayList<AppIdAndNameTransportModel>();
225         }
226
227         @Override
228         public EPApp getAppDetail(String appName) {
229                 final Map<String, String> params = new HashMap<String, String>();
230                 try {
231                         params.put("appName", appName);
232                         @SuppressWarnings("unchecked")
233                         List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
234                         return (apps.size() > 0) ? apps.get(0) : null;
235                 } catch (Exception e) {
236                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
237                         return null;
238                 }
239         }
240
241         @SuppressWarnings("unchecked")
242         @Override
243         public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
244                 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
245                         String format = "";
246                         String sql = "";
247                         if (adminRolesService.isSuperAdmin(user)) {
248                                 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
249                                                 + "where app.ENABLED = 'Y' AND app.app_type = 1";
250                         } else {
251                                 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 "
252                                                 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
253                                                 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
254                         }
255                         sql = String.format(format, user.getId());
256                         // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
257                         // app.APP_REST_ENDPOINT <> ''";
258                         logQuery(sql);
259                         try {
260                                 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
261                         } catch (Exception e) {
262                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
263                                 logger.error(EELFLoggerDelegate.errorLogger,
264                                                 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
265                         }
266                 }
267                 return new ArrayList<AppIdAndNameTransportModel>();
268         }
269
270         protected void logQuery(String sql) {
271                 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
272         }
273
274         public DataAccessService getDataAccessService() {
275                 return dataAccessService;
276         }
277
278         public void setDataAccessService(DataAccessService dataAccessService) {
279                 this.dataAccessService = dataAccessService;
280         }
281
282         @SuppressWarnings("unchecked")
283         @Override
284         public List<AdminUserApplications> getAppsAdmins() {
285                 try {
286                         Map<String, String> params = new HashMap<>();
287                         params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
288                         List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
289                                         params, null);
290                         return aggregateRowsResultsByUserId(adminApps);
291                 } catch (Exception e) {
292                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
293                         return null;
294                 }
295         }
296
297         private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
298                 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
299                 for (AdminUserApp app : adminApps) {
300                         Long userId = app.getUser_Id();
301                         if (adminUserApplications.get(userId) == null)
302                                 adminUserApplications.put(userId, new AdminUserApplications(app));
303                         else
304                                 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
305                 }
306                 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
307         }
308
309         @Override
310         public List<AppsResponse> getAllApps(Boolean all) {
311                 // If all is true, return both active and inactive apps. Otherwise, just
312                 // active apps.
313                 @SuppressWarnings("unchecked")
314                 // Sort the list by application name so the drop-down looks pretty.
315                 List<EPApp> apps = all
316                                 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
317                                 : (List<EPApp>) dataAccessService.getList(EPApp.class,
318                                                 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
319
320                 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
321                 for (EPApp app : apps) {
322                         appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
323                 }
324                 return appsModified;
325         }
326
327         @Override
328         public UserRoles getUserProfile(String loginId) {
329                 final Map<String, String> params = new HashMap<>();
330                 params.put("org_user_id", loginId);
331                 @SuppressWarnings("unchecked")
332                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
333                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
334                 if (usersRolesList == null || usersRolesList.size() < 1)
335                         return null;
336
337                 return usersRolesList.get(0);
338         }
339
340         @Override
341         public UserRoles getUserProfileNormalized(EPUser user) {
342                 // Check database.
343                 UserRoles userAndRoles = getUserProfile(user.getLoginId());
344                 // If no roles are defined, treat this user as a guest.
345                 if (user.isGuest() || userAndRoles == null) {
346                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
347                                         user.getLoginId());
348                         UserRole userRole = new UserRole();
349                         userRole.setUser_Id(user.getId());
350                         userRole.setOrgUserId(user.getLoginId());
351                         userRole.setFirstName(user.getFirstName());
352                         userRole.setLastName(user.getLastName());
353                         userRole.setRoleId(-1L);
354                         userRole.setRoleName("Guest");
355                         userRole.setUser_Id(-1L);
356                         userAndRoles = new UserRoles(userRole);
357                 }
358
359                 return userAndRoles;
360         }
361
362         protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
363                 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
364                 for (UserRole user : userRoleList) {
365                         String orgUserId = user.getOrgUserId();
366                         if (userRoles.get(orgUserId) == null)
367                                 userRoles.put(orgUserId, new UserRoles(user));
368                         else
369                                 userRoles.get(orgUserId).addRole(user.getRoleName());
370                 }
371                 return new ArrayList<UserRoles>(userRoles.values());
372         }
373
374         private boolean isRestrictedApp(Long appId) {
375                 EPApp app = getApp(appId);
376                 return app.isRestrictedApp();
377         }
378
379         // For the functional menu edit
380         @Override
381         public List<LocalRole> getAppRoles(Long appId) {
382                 String sql = "";
383                 if (isRestrictedApp(appId)) {
384                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
385                 }else if(appId == 1){
386                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
387                 }else{
388                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
389                 }
390                 logQuery(sql);
391                 @SuppressWarnings("unchecked")
392                 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
393                 return appRoles;
394         }
395
396         protected String userAppsQuery(EPUser user) {
397                 StringBuilder query = new StringBuilder();
398                 if (adminRolesService.isSuperAdmin(user)) {
399                         query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
400                 } else {
401                         query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
402                         query.append(
403                                         "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
404                         query.append(" AND FN_APP.ENABLED = 'Y'");
405                 }
406                 return query.toString();
407         }
408
409         protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
410                 FieldsValidator fieldsValidator = new FieldsValidator();
411                 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
412                                 || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
413                                 || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
414                                 || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID))
415                                 // For a normal app (appType==1), these fields must be filled
416                                 // in.
417                                 // For a restricted app (appType==2), they will be empty.
418                                 || ((!onboardingApp.restrictedApp)
419                                                 && (onboardingApp.username == null || onboardingApp.username.length() == 0
420                                                                 || onboardingApp.appPassword == null || onboardingApp.appPassword.length() == 0))) {
421                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
422                 }
423                 return fieldsValidator;
424         }
425
426         @Override
427         public List<EPApp> getUserApps(EPUser user) {
428                 List<EPApp> openApps = getOpenApps();
429
430                 if (user.isGuest()) {
431                         return openApps;
432                 } else {
433                         String sql = userAppsQuery(user);
434                         logQuery(sql);
435
436                         // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
437                         List<EPApp> appsList = new ArrayList<>();
438                         @SuppressWarnings("unchecked")
439                         List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
440                         HashSet<EPApp> appSet = new HashSet<>();
441                         for (EPApp app : adminApps) {
442                                 appSet.add(app);
443                                 appsList.add(app);
444                         }
445
446                         for (EPApp app : openApps) {
447                                 if (!appSet.contains(app))
448                                         appsList.add(app);
449                         }
450
451                         return appsList;
452                 }
453         }
454
455         @Override
456         public List<EPApp> getPersAdminApps(EPUser user) {
457                 final Map<String, Long> params = new HashMap<>();
458                 params.put("userId", user.getId());
459                 // Named query is stored in EP.hbm.xml, mapped to EPApp
460                 @SuppressWarnings("unchecked")
461                 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
462                 return list;
463         }
464
465         @Override
466         public List<EPApp> getPersUserApps(EPUser user) {
467                 final Map<String, Long> params = new HashMap<>();
468                 params.put("userId", user.getId());
469                 // Named query is stored in EP.hbm.xml, mapped to EPApp
470                 @SuppressWarnings("unchecked")
471                 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
472                 return list;
473         }
474
475         /*
476          * (non-Javadoc)
477          *
478          * @see
479          * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog(
480          * org.openecomp.portalapp.portal.domain.EPUser)
481          */
482         @Override
483         public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
484                 final Map<String, Long> params = new HashMap<>();
485                 params.put("userId", user.getId());
486                 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
487                 @SuppressWarnings("unchecked")
488                 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
489                 return list;
490         }
491
492         /*
493          * (non-Javadoc)
494          *
495          * @see
496          * org.openecomp.portalapp.portal.service.EPAppService#getAdminAppCatalog(
497          * org.openecomp.portalapp.portal.domain.EPUser)
498          */
499         @Override
500         public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
501                 final Map<String, Long> params = new HashMap<>();
502                 params.put("userId", user.getId());
503                 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
504                 @SuppressWarnings("unchecked")
505                 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
506                 return list;
507         }
508
509         private List<EPApp> getOpenApps() {
510                 @SuppressWarnings("unchecked")
511                 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
512                 return openApps;
513         }
514
515         @SuppressWarnings("unchecked")
516         @Override
517         public List<EPApp> getAppsOrderByName(EPUser user) {
518                 final Map<String, Long> params = new HashMap<>();
519                 List<EPApp> sortedAppsByName = null;
520                 try {
521                         if (adminRolesService.isSuperAdmin(user)) {
522                                 params.put("userId", user.getId());
523                                 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
524                         } else {
525                                 params.put("userId", user.getId());
526                                 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
527                         }
528                 } catch (Exception e) {
529                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
530                 }
531                 return sortedAppsByName;
532         }
533
534         @SuppressWarnings("unchecked")
535         @Override
536         public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
537
538                 final Map<String, Long> params = new HashMap<>();
539                 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
540                 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
541                 try {
542                         if (adminRolesService.isSuperAdmin(user)) {
543                                 params.put("userId", user.getId());
544                                 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
545                         } else {
546                                 params.put("userId", user.getId());
547                                 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
548                         }
549                         Set<String> epAppSet = new HashSet<String>();
550                         for (EPApp eapp : sortedAppsByLastUsed)
551                                 if (!epAppSet.contains(eapp.getName())) {
552                                         finalsortedAppsByLastUsed.add(eapp);
553                                         epAppSet.add(eapp.getName());
554                                 }
555
556                 } catch (Exception e) {
557                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
558                 }
559                 return finalsortedAppsByLastUsed;
560         }
561
562         @SuppressWarnings("unchecked")
563         @Override
564         public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
565                 final Map<String, Long> params = new HashMap<>();
566                 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
567                 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
568                 try {
569                         if (adminRolesService.isSuperAdmin(user)) {
570                                 params.put("userId", user.getId());
571                                 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
572                         } else {
573                                 params.put("userId", user.getId());
574                                 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
575                         }
576                         Set<String> epAppSet = new HashSet<String>();
577
578                         for (EPApp eapp : sortedAppsByMostUsed) {
579                                 if (!epAppSet.contains(eapp.getName())) {
580                                         finalsortedAppsByMostUsed.add(eapp);
581                                         epAppSet.add(eapp.getName());
582                                 }
583                         }
584                 } catch (Exception e) {
585                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
586                 }
587
588                 return finalsortedAppsByMostUsed;
589         }
590
591         /*
592          * This Method retrieves the User Apps by Sort Manual Preference
593          *
594          * @param: user--contains LoggedIn User Data
595          */
596         @SuppressWarnings("unchecked")
597         @Override
598         public List<EPApp> getAppsOrderByManual(EPUser user) {
599                 final Map<String, Long> params = new HashMap<>();
600                 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
601                 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
602                 try {
603                         if (adminRolesService.isSuperAdmin(user)) {
604                                 params.put("userId", user.getId());
605                                 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
606                         } else {
607                                 params.put("userId", user.getId());
608                                 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
609                         }
610                         Set<String> epAppSet = new HashSet<String>();
611
612                         for (EPApp eapp : sortedAppsByManual) {
613                                 if (!epAppSet.contains(eapp.getName())) {
614                                         finalsortedAppsByManual.add(eapp);
615                                         epAppSet.add(eapp.getName());
616                                 }
617                         }
618                 } catch (Exception e) {
619                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
620                 }
621                 return finalsortedAppsByManual;
622         }
623
624         @Override
625         public List<OnboardingApp> getOnboardingApps() {
626                 @SuppressWarnings("unchecked")
627                 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
628                 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
629                 for (EPApp app : apps) {
630                         OnboardingApp onboardingApp = new OnboardingApp();
631                         createOnboardingFromApp(app, onboardingApp);
632                         onboardingAppsList.add(onboardingApp);
633                 }
634                 return onboardingAppsList;
635         }
636
637         @Override
638         public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
639                 @SuppressWarnings("unchecked")
640                 List<EPApp> apps = dataAccessService.getList(EPApp.class,
641                                 " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
642                 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
643                 for (EPApp app : apps) {
644                         OnboardingApp onboardingApp = new OnboardingApp();
645                         createOnboardingFromApp(app, onboardingApp);
646                         onboardingAppsList.add(onboardingApp);
647                 }
648                 return onboardingAppsList;
649         }
650
651         @SuppressWarnings("unchecked")
652         private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
653                 boolean duplicatedUrl = false;
654                 boolean duplicatedName = false;
655                 List<EPApp> apps;
656                 if (onboardingApp.id == null) {
657                         apps = dataAccessService.getList(EPApp.class,
658                                         " where url = '" + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null);
659                 } else {
660                         apps = dataAccessService.getList(EPApp.class, " where id = " + onboardingApp.id + " or url = '"
661                                         + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null);
662                 }
663                 for (EPApp app : apps) {
664                         if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) {
665                                 continue;
666                         }
667                         if (!duplicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) {
668                                 duplicatedUrl = true;
669                                 if (duplicatedName) {
670                                         break;
671                                 }
672                         }
673                         if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
674                                 duplicatedName = true;
675                                 if (duplicatedUrl) {
676                                         break;
677                                 }
678                         }
679                 }
680                 if (duplicatedUrl || duplicatedName) {
681                         if (duplicatedUrl) {
682                                 fieldsValidator.addProblematicFieldName(urlField);
683                         }
684                         if (duplicatedName) {
685                                 fieldsValidator.addProblematicFieldName(nameField);
686                         }
687                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
688                         fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
689                 }
690         }
691
692         @Override
693         public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
694                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
695                 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
696                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
697                         validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
698                 }
699                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
700                         if (modifiedOnboardingApp.id != null) {
701                                 updateApp(modifiedOnboardingApp.id, modifiedOnboardingApp, fieldsValidator, user);
702                         } else {
703                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
704                         }
705                 }
706                 return fieldsValidator;
707         }
708
709         @Override
710         public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
711                 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
712                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
713                         validateOnboardingApp(newOnboardingApp, fieldsValidator);
714                 }
715                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
716                         if (newOnboardingApp.id == null) {
717                                 updateApp(null, newOnboardingApp, fieldsValidator, user);
718                         } else {
719                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
720                         }
721                 }
722                 return fieldsValidator;
723         }
724
725         @SuppressWarnings("unchecked")
726         @Override
727         public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
728                 FieldsValidator fieldsValidator = new FieldsValidator();
729                 if (!adminRolesService.isSuperAdmin(user)) {
730                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
731                         return fieldsValidator;
732                 }
733                 final Map<String, Long> params = new HashMap<>();
734                 params.put("app_id", appid);
735                 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
736                 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
737             for(int i=0;i<EPUserAppRolesRequestList.size();i++)
738             {
739              dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
740                 
741             }
742                 
743                 Boolean result = false;
744                 Session localSession = null;
745                 Transaction transaction = null;
746                 try {
747                         localSession = sessionFactory.openSession();
748                         transaction = localSession.beginTransaction();
749
750                         // 1) Remove the URL for any functional menu item associated with
751                         // this app
752                         String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
753                                         + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
754                         logQuery(sql);
755                         Query query = localSession.createSQLQuery(sql);
756                         query.executeUpdate();
757
758                         // Remove any favorites associated with a menu item that is
759                         // associated with this app
760                         sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
761                                         + " where fn_menu_functional_roles.app_id='" + appid + "' "
762                                         + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
763                         logQuery(sql);
764                         query = localSession.createSQLQuery(sql);
765                         query.executeUpdate();
766
767                         // Remove all role, appid records from fn_menu_functional_role
768                         // that are associated with this app
769                         sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
770                         logQuery(sql);
771                         query = localSession.createSQLQuery(sql);
772                         query.executeUpdate();
773
774                         // Remove all records from fn_user_role associated with this app
775                         sql = "delete from fn_user_role where app_id='" + appid + "'";
776                         logQuery(sql);
777                         query = localSession.createSQLQuery(sql);
778                         query.executeUpdate();
779
780                         // Remove any widgets associated with this app
781                         sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
782                         logQuery(sql);
783                         query = localSession.createSQLQuery(sql);
784                         query.executeUpdate();
785
786                         // Remove any roles associated with this app
787                         sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
788                                         + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
789                         logQuery(sql);
790                         query = localSession.createSQLQuery(sql);
791                         query.executeUpdate();
792
793                         // Remove all records from fn_role associated with this app
794                         sql = "delete from fn_role where app_id='" + appid + "'";
795                         logQuery(sql);
796                         query = localSession.createSQLQuery(sql);
797                         query.executeUpdate();
798
799                         // Remove app contact us entries
800                         sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
801                         logQuery(sql);
802                         query = localSession.createSQLQuery(sql);
803                         query.executeUpdate();
804
805                         // Remove rows in the app personalization selection table
806                         sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
807                         logQuery(sql);
808                         query = localSession.createSQLQuery(sql);
809                         query.executeUpdate();
810
811                         // Remove rows in the app personalization sort table
812                         sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
813                         logQuery(sql);
814                         query = localSession.createSQLQuery(sql);
815                         query.executeUpdate();
816
817                         // Remove rows in the app personalization sort table
818                         sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
819                         logQuery(sql);
820                         query = localSession.createSQLQuery(sql);
821                         query.executeUpdate();
822
823                         // Remove rows in the app personalization sort table
824                         sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
825                         logQuery(sql);
826                         query = localSession.createSQLQuery(sql);
827                         query.executeUpdate();
828
829                         // Delete the app
830                         sql = "delete from fn_app where app_id='" + appid + "'";
831                         logQuery(sql);
832                         query = localSession.createSQLQuery(sql);
833                         query.executeUpdate();
834
835                         transaction.commit();
836                         result = true;
837                 } catch (Exception e) {
838                         logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
839                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
840                         EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
841                 } finally {
842                         EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
843                 }
844                 if (!result) {
845                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
846                 }
847                 return fieldsValidator;
848         }
849
850         private static Object syncRests = new Object();
851
852         // An app has been enabled/disabled. Must enable/disable all associated
853         // functional menu items.
854         protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
855                 String active_yn = enabled ? "Y" : "N";
856                 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
857                                 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
858                                 + " AND r.app_id = '" + appId + "' ";
859                 logQuery(sql);
860                 @SuppressWarnings("unchecked")
861                 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
862                 for (FunctionalMenuItem menuItem : menuItems) {
863                         FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
864                                         menuItem.menuId);
865                         myMenuItem.active_yn = active_yn;
866                         localSession.save(myMenuItem);
867                 }
868         }
869
870         // Attention! If (appId == null) we use this function to create application
871         // otherwise we use it to modify existing application
872         protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
873                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
874                 // Separate out the code for a restricted app, since it doesn't need any
875                 // of the UEB code.
876                 if (onboardingApp.restrictedApp) {
877                         boolean result = false;
878                         Session localSession = null;
879                         Transaction transaction = null;
880                         try {
881                                 localSession = sessionFactory.openSession();
882                                 transaction = localSession.beginTransaction();
883                                 EPApp app;
884                                 if (appId == null) {
885                                         app = new EPApp();
886                                 } else {
887                                         app = (EPApp) localSession.get(EPApp.class, appId);
888                                         if (app == null || app.getId() == null) { // App is already
889                                                 // deleted!
890                                                 transaction.commit();
891                                                 localSession.close();
892                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
893                                                 return;
894                                         }
895                                 }
896                                 createAppFromOnboarding(app, onboardingApp, localSession);
897                                 localSession.saveOrUpdate(app);
898                                 // Enable or disable all menu items associated with this app
899                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
900                                 transaction.commit();
901                                 result = true;
902                         } catch (Exception e) {
903                                 EcompPortalUtils.rollbackTransaction(transaction,
904                                                 "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e));
905                         } finally {
906                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
907                         }
908                         if (!result) {
909                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
910                         }
911
912                 } else {
913                         updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
914                         
915                 }
916         }
917
918         protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
919                         EPUser user) {
920                 synchronized (syncRests) {
921                         boolean result = false;
922                         Session localSession = null;
923                         Transaction transaction = null;
924                         try {
925                                 localSession = sessionFactory.openSession();
926                                 transaction = localSession.beginTransaction();
927                                 EPApp app;
928                                 if (appId == null) {
929                                         app = new EPApp();
930                                         // -------------------------------------------------------------------------------------------
931                                         // Register this App with the UEB communication server.
932                                         // Save
933                                         // the App's unique mailbox/topic
934                                         // name and keys to the FN_APP table. The App's mailbox
935                                         // and
936                                         // keys will be visible to the
937                                         // admin on the ECOMP portal.
938                                         // -------------------------------------------------------------------------------------------
939                                         TopicManager topicManager = new TopicManager() {
940
941                                                 EPAppCommonServiceImpl service;
942
943                                                 public void init(EPAppCommonServiceImpl _service) {
944                                                         service = _service;
945                                                 }
946
947                                                 public void createTopic(String key, String secret, String topicName,
948                                                                 String topicDescription) throws HttpException, CambriaApiException, IOException {
949
950                                                         init(EPAppCommonServiceImpl.this);
951                                                         final LinkedList<String> urlList = Helper.uebUrlList();
952                                                         if (logger.isInfoEnabled()) {
953                                                                 logger.info("==> createTopic");
954                                                                 logger.info("topicName: " + topicName);
955                                                                 logger.info("topicDescription: " + topicDescription);
956                                                         }
957                                                         CambriaTopicManager tm = null;
958                                                         try {
959                                                                 tm = service.getTopicManager(urlList, key, secret);
960                                                         } catch (Exception e) {
961                                                                 logger.error("pub.build Exception ", e);
962                                                                 throw new CambriaApiException(topicName);
963                                                         }
964                                                         tm.createTopic(topicName, topicDescription, 1, 1);
965                                                 }
966
967                                                 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
968                                                                 String topicName) throws HttpException, CambriaApiException, IOException {
969                                                         logger.info("==> addPublisher to topic " + topicName);
970                                                         final LinkedList<String> urlList = Helper.uebUrlList();
971                                                         CambriaTopicManager tm = null;
972                                                         try {
973                                                                 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
974                                                         } catch (Exception e) {
975                                                                 logger.error("pub.build Exception ", e);
976                                                                 throw new CambriaApiException(topicName);
977                                                         }
978                                                         tm.allowProducer(topicName, publisherKey);
979                                                 }
980
981                                         };
982                                         final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
983                                                         .usingHosts(Helper.uebUrlList()).build();
984                                         com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
985                                                         "ECOMP Portal Owner");
986                                         String appKey = credential.getApiKey();
987                                         String appSecret = credential.getApiSecret();
988                                         String appMailboxName = null;
989
990                                         int maxNumAttemptsToCreateATopic = 3;
991                                         boolean successfullyCreatedMailbox = false;
992                                         for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
993                                                 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
994
995                                                 try {
996                                                         topicManager.createTopic(
997                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
998                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
999                                                                         appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
1000                                                         successfullyCreatedMailbox = true;
1001                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1002                                                                         "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
1003                                                         logger.debug(EELFLoggerDelegate.debugLogger, "    Key = " + appKey + " Secret = "
1004                                                                         + appSecret + " generated using = " + user.getEmail());
1005                                                         break;
1006                                                 } catch (HttpException e) {
1007                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1008                                                         if (e.getStatusCode() == 409) {
1009                                                                 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1010                                                                                 + " already exists. Will try using a different name", e);
1011                                                         } else {
1012                                                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1013                                                                                 e);
1014                                                         }
1015                                                 }
1016                                         }
1017
1018                                         if (successfullyCreatedMailbox) {
1019                                                 onboardingApp.setUebTopicName(appMailboxName);
1020                                                 onboardingApp.setUebKey(appKey);
1021                                                 onboardingApp.setUebSecret(appSecret);
1022
1023                                                 try {
1024                                                         /*
1025                                                          * EP is a publisher to this App's new mailbox
1026                                                          */
1027                                                         topicManager.addPublisher(
1028                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1029                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1030                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1031                                                                         appMailboxName);
1032
1033                                                         /*
1034                                                          * This App is a subscriber of its own mailbox
1035                                                          */
1036                                                         topicManager.addSubscriber(
1037                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1038                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1039                                                                         appMailboxName);
1040
1041                                                         /*
1042                                                          * This App is a publisher to EP
1043                                                          */
1044                                                         topicManager.addPublisher(
1045                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1046                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1047                                                                         PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1048                                                 } catch (HttpException | CambriaApiException | IOException e) {
1049                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1050                                                         logger.error(EELFLoggerDelegate.errorLogger,
1051                                                                         "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1052                                                         transaction.commit();
1053                                                         localSession.close();
1054                                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1055                                                         return;
1056                                                 }
1057                                         } else {
1058                                                 transaction.commit();
1059                                                 localSession.close();
1060                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1061                                                 return;
1062                                         }
1063                                 } else {
1064                                         app = (EPApp) localSession.get(EPApp.class, appId);
1065                                         if (app == null || app.getId() == null) {
1066                                                 // App is already deleted!
1067                                                 transaction.commit();
1068                                                 localSession.close();
1069                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1070                                                 return;
1071                                         }
1072                                 }
1073                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1074                                 createAppFromOnboarding(app, onboardingApp, localSession);
1075                                 logger.debug(EELFLoggerDelegate.debugLogger,
1076                                                 "LR: updateApp: finished calling createAppFromOnboarding");
1077                                 localSession.saveOrUpdate(app);
1078                                 logger.debug(EELFLoggerDelegate.debugLogger,
1079                                                 "LR: updateApp: finished calling localSession.saveOrUpdate");
1080                                 // Enable or disable all menu items associated with this app
1081                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1082                                 logger.debug(EELFLoggerDelegate.debugLogger,
1083                                                 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1084                                 transaction.commit();
1085                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1086                                 epUebHelper.addPublisher(app);
1087                                 logger.debug(EELFLoggerDelegate.debugLogger,
1088                                                 "LR: updateApp: finished calling epUebHelper.addPublisher");
1089                                 result = true;
1090                         } catch (Exception e) {
1091                                 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1092                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1093                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1094                                 EcompPortalUtils.rollbackTransaction(transaction,
1095                                                 "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e));
1096                         } finally {
1097                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1098                         }
1099                         if (!result) {
1100                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1101                         }
1102                 }
1103
1104         }
1105
1106         public CambriaTopicManager getTopicManager(LinkedList<String> urlList, String key, String secret)
1107                         throws GeneralSecurityException, Exception {
1108                 throw new Exception("This method can only be invoked from child class");
1109         }
1110
1111         /**
1112          * Populates a transport model of the application from a database row model.
1113          * Leaves out the thumbnail because the FE fetches images via a different
1114          * API.
1115          * 
1116          * @param app
1117          *            Model of database row
1118          * @param onboardingApp
1119          *            Model for transport as JSON
1120          */
1121         @Override
1122         public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1123                 onboardingApp.id = app.getId();
1124                 onboardingApp.name = app.getName();
1125                 onboardingApp.imageUrl = app.getImageUrl();
1126                 onboardingApp.description = app.getDescription();
1127                 onboardingApp.notes = app.getNotes();
1128                 onboardingApp.url = app.getUrl();
1129                 onboardingApp.alternateUrl = app.getAlternateUrl();
1130                 onboardingApp.restUrl = app.getAppRestEndpoint();
1131                 onboardingApp.isOpen = app.getOpen();
1132                 onboardingApp.isEnabled = app.getEnabled();
1133                 onboardingApp.username = app.getUsername();
1134                 onboardingApp.appPassword = decryptedPassword(app.getAppPassword(), app);
1135                 onboardingApp.uebTopicName = app.getUebTopicName();
1136                 onboardingApp.uebKey = app.getUebKey();
1137                 onboardingApp.uebSecret = app.getUebSecret();
1138                 onboardingApp.isCentralAuth = app.getCentralAuth();
1139                 onboardingApp.nameSpace = app.getNameSpace();
1140                 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1141                 // if (app.getThumbnail() != null)
1142                 // onboardingApp.thumbnail = new
1143                 // String(Base64.getEncoder().encode(app.getThumbnail()));
1144         }
1145
1146         /**
1147          * Creates a database object for an application from an uploaded transport
1148          * model. Must decode the thumbnail, if any.
1149          * 
1150          * @param app
1151          * @param onboardingApp
1152          * @param localSession
1153          * @return The first argument.
1154          */
1155         protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1156                 app.setName(onboardingApp.name);
1157                 app.setDescription(onboardingApp.description);
1158                 app.setNotes(onboardingApp.notes);
1159                 app.setUrl(onboardingApp.url);
1160                 app.setAlternateUrl(onboardingApp.alternateUrl);
1161                 app.setAppRestEndpoint(onboardingApp.restUrl);
1162                 app.setOpen(onboardingApp.isOpen);
1163                 app.setEnabled(onboardingApp.isEnabled);
1164                 app.setUsername(onboardingApp.username);
1165                 app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
1166                 app.setUebTopicName(onboardingApp.uebTopicName);
1167                 app.setUebKey(onboardingApp.uebKey);
1168                 app.setUebSecret(onboardingApp.uebSecret);
1169                 app.setCentralAuth(onboardingApp.isCentralAuth);
1170                 app.setNameSpace(onboardingApp.nameSpace);
1171                 app.setRestrictedApp(onboardingApp.restrictedApp);
1172                 if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
1173                         logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1174                         String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
1175                         logger.debug(EELFLoggerDelegate.debugLogger,
1176                                         "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1177                         if (splitBase64Thumbnail.length > 1) {
1178                                 // This occurs when we have a new image, not an existing image
1179                                 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1180                                 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1181                                 // This is basically a boolean indicator that an image is
1182                                 // present.
1183                                 app.setImageUrl(constructImageName(onboardingApp));
1184                                 app.setThumbnail(decodedImage);
1185                         }
1186                 } else if (app.getThumbnail() != null && onboardingApp.imageLink == null) {
1187                         // The thumbnail that came in from the json is empty; the previous
1188                         // thumbnail is NOT empty. Must delete it.
1189                         logger.debug(EELFLoggerDelegate.debugLogger,
1190                                         "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1191                         app.setImageUrl(null);
1192                         app.setThumbnail(null);
1193                 } else {
1194                         logger.debug(EELFLoggerDelegate.debugLogger,
1195                                         "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1196                 }
1197                 return app;
1198         }
1199
1200         protected String constructImageName(OnboardingApp onboardingApp) {
1201                 return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
1202                                 + ".png";
1203         }
1204
1205         // Don't encrypt or decrypt the password if it is null or the empty string
1206         private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1207                 String result = "";
1208                 if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) {
1209                         try {
1210                                 result = CipherUtil.decrypt(encryptedAppPwd,
1211                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1212                         } catch (Exception e) {
1213                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1214                         }
1215                 }
1216                 return result;
1217         }
1218
1219         protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1220                 String result = "";
1221                 if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) {
1222                         try {
1223                                 result = CipherUtil.encrypt(decryptedAppPwd,
1224                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1225                         } catch (Exception e) {
1226                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1227                         }
1228                 }
1229                 return result;
1230         }
1231
1232         @SuppressWarnings("unchecked")
1233         @Override
1234         public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1235                 FieldsValidator fieldsValidator = new FieldsValidator();
1236                 final Map<String, Long> params = new HashMap<>();
1237                 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1238
1239                 try {
1240                         params.put("userId", user.getId());
1241                         epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1242                         Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1243                         for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1244                                 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1245                         }
1246                         for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1247                                 if (epWidgetsManPref.getWidgetid() != null) {
1248                                         Long widgetid = epWidgetsManPref.getWidgetid();
1249                                         if (existingWidgetsIds.containsKey(widgetid)) {
1250                                                 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1251                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1252                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1253                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1254                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1255                                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1256                                                 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1257                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1258                                         } else {
1259                                                 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1260                                                 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1261                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1262                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1263                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1264                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1265                                                 epWidgetsManualSort.setUserId(Ints.checkedCast(user.getId()));
1266                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1267                                         }
1268                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1269                                 }
1270                         }
1271                 } catch (Exception e) {
1272                         logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1273                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1274                 }
1275                 return fieldsValidator;
1276         }
1277
1278         @SuppressWarnings("unchecked")
1279         @Override
1280         public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1281                 FieldsValidator fieldsValidator = new FieldsValidator();
1282                 final Map<String, Long> params = new HashMap<>();
1283                 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1284                 try {
1285                         params.put("userId", user.getId());
1286                         epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1287                         Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1288                         for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1289                                 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1290                         }
1291                         for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1292                                 if (delEpWidgetsManPref.getWidgetid() != null) {
1293                                         Long widgetId = delEpWidgetsManPref.getWidgetid();
1294                                         if (existingWidgetIds.containsKey(widgetId)) {
1295                                                 dataAccessService.deleteDomainObjects(EPWidgetsManualSortPreference.class,
1296                                                                 "widget_id=" + widgetId + " AND user_id=" + user.getId(), null);
1297                                         }
1298                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1299                                 }
1300                         }
1301                 } catch (Exception e) {
1302                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1303                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1304                 }
1305                 return fieldsValidator;
1306         }
1307
1308         /*
1309          * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1310          *
1311          * @param: appsSortManual--contains User Apps Data
1312          *
1313          * @param: user--contains LoggedIn User Data
1314          */
1315         @SuppressWarnings("unchecked")
1316         @Override
1317         public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1318                 FieldsValidator fieldsValidator = new FieldsValidator();
1319                 final Map<String, Long> params = new HashMap<>();
1320                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1321
1322                 try {
1323                         params.put("userId", user.getId());
1324                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1325                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1326                         for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1327                                 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1328                         }
1329                         for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1330                                 if (epAppsManPref.getAppid() != null) {
1331                                         Long appid = epAppsManPref.getAppid();
1332                                         if (existingAppIds.containsKey(appid)) {
1333                                                 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1334                                                 epAppsManualSort
1335                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1336                                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1337                                                 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1338                                                 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1339                                         } else {
1340                                                 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1341                                                 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1342                                                 epAppsManualSort
1343                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1344                                                 epAppsManualSort.setUserId(Ints.checkedCast(user.getId()));
1345                                                 dataAccessService.saveDomainObject(epAppsManualSort, null);
1346                                         }
1347                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1348                                 }
1349                         }
1350                 } catch (Exception e) {
1351                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1352                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1353                 }
1354                 return fieldsValidator;
1355         }
1356
1357         /*
1358          * (non-Javadoc)
1359          *
1360          * @see org.openecomp.portalapp.portal.service.EPAppService#
1361          * deleteUserAppSortManual(java.lang.String,
1362          * org.openecomp.portalapp.portal.domain.EPUser)
1363          */
1364         @SuppressWarnings("unchecked")
1365         @Override
1366         public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1367                 FieldsValidator fieldsValidator = new FieldsValidator();
1368                 final Map<String, Long> params = new HashMap<>();
1369                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1370                 try {
1371                         params.put("userId", user.getId());
1372                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1373                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1374                         for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1375                                 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1376                         }
1377                         if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1378                                 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1379                                                 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1380                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1381                         }
1382                 } catch (Exception e) {
1383                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1384                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1385                 }
1386                 return fieldsValidator;
1387         }
1388
1389         @SuppressWarnings("unchecked")
1390         @Override
1391         public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1392                 FieldsValidator fieldsValidator = new FieldsValidator();
1393                 final Map<String, Long> params = new HashMap<>();
1394                 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1395                 EPUserAppsSortPreference usrSortPr = null;
1396                 try {
1397                         params.put("userId", user.getId());
1398                         epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1399                         if (epSortTypes.size() == 0) {
1400                                 usrSortPr = new EPUserAppsSortPreference();
1401                                 usrSortPr.setUserId(Ints.checkedCast(user.getId()));
1402                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1403                                 dataAccessService.saveDomainObject(usrSortPr, null);
1404                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1405                         } else {
1406                                 usrSortPr = epSortTypes.get(0);
1407                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1408                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1409                                 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1410                                 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1411                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1412                         }
1413                 } catch (Exception e) {
1414                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1415                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1416                 }
1417                 return fieldsValidator;
1418         }
1419
1420         @SuppressWarnings("unchecked")
1421         @Override
1422         public String getUserAppsSortTypePreference(EPUser user) {
1423                 final Map<String, Long> params = new HashMap<>();
1424                 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1425                 try {
1426                         params.put("userId", user.getId());
1427                         userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1428                         if (userSortPrefs.size() > 0)
1429                                 return userSortPrefs.get(0).getSortPref();
1430                         else
1431                                 return null;
1432                 } catch (Exception e) {
1433                         logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1434                 }
1435                 return null;
1436
1437         }
1438
1439         @Override
1440         public List<EPApp> getUserRemoteApps(String id) {
1441                 throw new RuntimeException(" Cannot be called from parent class");
1442         }
1443         
1444         @Override
1445         public UserRoles getUserProfileForLeftMenu(String loginId) {
1446                 final Map<String, String> params = new HashMap<>();
1447                 params.put("org_user_id", loginId);
1448                 @SuppressWarnings("unchecked")
1449                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1450                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1451                 if (usersRolesList == null || usersRolesList.size() < 1)
1452                         return null;
1453
1454                 return usersRolesList.get(0);
1455         }
1456         
1457         
1458         @Override
1459         public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1460                 // Check database.
1461                 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1462                 // If no roles are defined, treat this user as a guest.
1463                 if (user.isGuest() || userAndRoles == null) {
1464                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1465                                         user.getLoginId());
1466                         UserRole userRole = new UserRole();
1467                         userRole.setUser_Id(user.getId());
1468                         userRole.setOrgUserId(user.getLoginId());
1469                         userRole.setFirstName(user.getFirstName());
1470                         userRole.setLastName(user.getLastName());
1471                         userRole.setRoleId(-1L);
1472                         userRole.setRoleName("Guest");
1473                         userRole.setUser_Id(-1L);
1474                         userAndRoles = new UserRoles(userRole);
1475                 }
1476
1477                 return userAndRoles;
1478         }
1479         
1480
1481 }