b51ea1a1ed669c3fc3b4d219d5547be3011bb4bd
[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                         
775                         // Remove all roles, rolefunctions, appid records from ep_app_role_function
776                         // that are associated with this app
777                     sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
778                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
779                          query = localSession.createSQLQuery(sql);
780                         query.executeUpdate();
781                         
782                         //Remove all rolefunctions, appid records from ep_app_function
783                         // that are associated with this app
784                         sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
785                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
786                         query = localSession.createSQLQuery(sql);
787                         query.executeUpdate();
788
789                         // Remove all records from fn_user_role associated with this app
790                         sql = "delete from fn_user_role where app_id='" + appid + "'";
791                         logQuery(sql);
792                         query = localSession.createSQLQuery(sql);
793                         query.executeUpdate();
794
795                         // Remove any widgets associated with this app
796                         sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
797                         logQuery(sql);
798                         query = localSession.createSQLQuery(sql);
799                         query.executeUpdate();
800
801                         // Remove any roles associated with this app
802                         sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
803                                         + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
804                         logQuery(sql);
805                         query = localSession.createSQLQuery(sql);
806                         query.executeUpdate();
807
808                         // Remove all records from fn_role associated with this app
809                         sql = "delete from fn_role where app_id='" + appid + "'";
810                         logQuery(sql);
811                         query = localSession.createSQLQuery(sql);
812                         query.executeUpdate();
813
814                         // Remove app contact us entries
815                         sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
816                         logQuery(sql);
817                         query = localSession.createSQLQuery(sql);
818                         query.executeUpdate();
819
820                         // Remove rows in the app personalization selection table
821                         sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
822                         logQuery(sql);
823                         query = localSession.createSQLQuery(sql);
824                         query.executeUpdate();
825
826                         // Remove rows in the app personalization sort table
827                         sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
828                         logQuery(sql);
829                         query = localSession.createSQLQuery(sql);
830                         query.executeUpdate();
831
832                         // Remove rows in the app personalization sort table
833                         sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
834                         logQuery(sql);
835                         query = localSession.createSQLQuery(sql);
836                         query.executeUpdate();
837
838                         // Remove rows in the app personalization sort table
839                         sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
840                         logQuery(sql);
841                         query = localSession.createSQLQuery(sql);
842                         query.executeUpdate();
843
844                         // Delete the app
845                         sql = "delete from fn_app where app_id='" + appid + "'";
846                         logQuery(sql);
847                         query = localSession.createSQLQuery(sql);
848                         query.executeUpdate();
849
850                         transaction.commit();
851                         result = true;
852                 } catch (Exception e) {
853                         logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
854                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
855                         EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
856                 } finally {
857                         EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
858                 }
859                 if (!result) {
860                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
861                 }
862                 return fieldsValidator;
863         }
864
865         private static Object syncRests = new Object();
866
867         // An app has been enabled/disabled. Must enable/disable all associated
868         // functional menu items.
869         protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
870                 String active_yn = enabled ? "Y" : "N";
871                 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
872                                 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
873                                 + " AND r.app_id = '" + appId + "' ";
874                 logQuery(sql);
875                 @SuppressWarnings("unchecked")
876                 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
877                 for (FunctionalMenuItem menuItem : menuItems) {
878                         FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
879                                         menuItem.menuId);
880                         myMenuItem.active_yn = active_yn;
881                         localSession.save(myMenuItem);
882                 }
883         }
884
885         // Attention! If (appId == null) we use this function to create application
886         // otherwise we use it to modify existing application
887         protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
888                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
889                 // Separate out the code for a restricted app, since it doesn't need any
890                 // of the UEB code.
891                 if (onboardingApp.restrictedApp) {
892                         boolean result = false;
893                         Session localSession = null;
894                         Transaction transaction = null;
895                         try {
896                                 localSession = sessionFactory.openSession();
897                                 transaction = localSession.beginTransaction();
898                                 EPApp app;
899                                 if (appId == null) {
900                                         app = new EPApp();
901                                 } else {
902                                         app = (EPApp) localSession.get(EPApp.class, appId);
903                                         if (app == null || app.getId() == null) { // App is already
904                                                 // deleted!
905                                                 transaction.commit();
906                                                 localSession.close();
907                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
908                                                 return;
909                                         }
910                                 }
911                                 createAppFromOnboarding(app, onboardingApp, localSession);
912                                 localSession.saveOrUpdate(app);
913                                 // Enable or disable all menu items associated with this app
914                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
915                                 transaction.commit();
916                                 result = true;
917                         } catch (Exception e) {
918                                 EcompPortalUtils.rollbackTransaction(transaction,
919                                                 "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e));
920                         } finally {
921                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
922                         }
923                         if (!result) {
924                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
925                         }
926
927                 } else {
928                         updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
929                         
930                 }
931         }
932
933         protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
934                         EPUser user) {
935                 synchronized (syncRests) {
936                         boolean result = false;
937                         Session localSession = null;
938                         Transaction transaction = null;
939                         try {
940                                 localSession = sessionFactory.openSession();
941                                 transaction = localSession.beginTransaction();
942                                 EPApp app;
943                                 if (appId == null) {
944                                         app = new EPApp();
945                                         // -------------------------------------------------------------------------------------------
946                                         // Register this App with the UEB communication server.
947                                         // Save
948                                         // the App's unique mailbox/topic
949                                         // name and keys to the FN_APP table. The App's mailbox
950                                         // and
951                                         // keys will be visible to the
952                                         // admin on the ECOMP portal.
953                                         // -------------------------------------------------------------------------------------------
954                                         TopicManager topicManager = new TopicManager() {
955
956                                                 EPAppCommonServiceImpl service;
957
958                                                 public void init(EPAppCommonServiceImpl _service) {
959                                                         service = _service;
960                                                 }
961
962                                                 public void createTopic(String key, String secret, String topicName,
963                                                                 String topicDescription) throws HttpException, CambriaApiException, IOException {
964
965                                                         init(EPAppCommonServiceImpl.this);
966                                                         final LinkedList<String> urlList = Helper.uebUrlList();
967                                                         if (logger.isInfoEnabled()) {
968                                                                 logger.info("==> createTopic");
969                                                                 logger.info("topicName: " + topicName);
970                                                                 logger.info("topicDescription: " + topicDescription);
971                                                         }
972                                                         CambriaTopicManager tm = null;
973                                                         try {
974                                                                 tm = service.getTopicManager(urlList, key, secret);
975                                                         } catch (Exception e) {
976                                                                 logger.error("pub.build Exception ", e);
977                                                                 throw new CambriaApiException(topicName);
978                                                         }
979                                                         tm.createTopic(topicName, topicDescription, 1, 1);
980                                                 }
981
982                                                 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
983                                                                 String topicName) throws HttpException, CambriaApiException, IOException {
984                                                         logger.info("==> addPublisher to topic " + topicName);
985                                                         final LinkedList<String> urlList = Helper.uebUrlList();
986                                                         CambriaTopicManager tm = null;
987                                                         try {
988                                                                 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
989                                                         } catch (Exception e) {
990                                                                 logger.error("pub.build Exception ", e);
991                                                                 throw new CambriaApiException(topicName);
992                                                         }
993                                                         tm.allowProducer(topicName, publisherKey);
994                                                 }
995
996                                         };
997                                         final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
998                                                         .usingHosts(Helper.uebUrlList()).build();
999                                         com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1000                                                         "ECOMP Portal Owner");
1001                                         String appKey = credential.getApiKey();
1002                                         String appSecret = credential.getApiSecret();
1003                                         String appMailboxName = null;
1004
1005                                         int maxNumAttemptsToCreateATopic = 3;
1006                                         boolean successfullyCreatedMailbox = false;
1007                                         for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1008                                                 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1009
1010                                                 try {
1011                                                         topicManager.createTopic(
1012                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1013                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1014                                                                         appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
1015                                                         successfullyCreatedMailbox = true;
1016                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1017                                                                         "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
1018                                                         logger.debug(EELFLoggerDelegate.debugLogger, "    Key = " + appKey + " Secret = "
1019                                                                         + appSecret + " generated using = " + user.getEmail());
1020                                                         break;
1021                                                 } catch (HttpException e) {
1022                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1023                                                         if (e.getStatusCode() == 409) {
1024                                                                 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1025                                                                                 + " already exists. Will try using a different name", e);
1026                                                         } else {
1027                                                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1028                                                                                 e);
1029                                                         }
1030                                                 }
1031                                         }
1032
1033                                         if (successfullyCreatedMailbox) {
1034                                                 onboardingApp.setUebTopicName(appMailboxName);
1035                                                 onboardingApp.setUebKey(appKey);
1036                                                 onboardingApp.setUebSecret(appSecret);
1037
1038                                                 try {
1039                                                         /*
1040                                                          * EP is a publisher to this App's new mailbox
1041                                                          */
1042                                                         topicManager.addPublisher(
1043                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1044                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1045                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1046                                                                         appMailboxName);
1047
1048                                                         /*
1049                                                          * This App is a subscriber of its own mailbox
1050                                                          */
1051                                                         topicManager.addSubscriber(
1052                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1053                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1054                                                                         appMailboxName);
1055
1056                                                         /*
1057                                                          * This App is a publisher to EP
1058                                                          */
1059                                                         topicManager.addPublisher(
1060                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1061                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1062                                                                         PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1063                                                 } catch (HttpException | CambriaApiException | IOException e) {
1064                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1065                                                         logger.error(EELFLoggerDelegate.errorLogger,
1066                                                                         "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1067                                                         transaction.commit();
1068                                                         localSession.close();
1069                                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1070                                                         return;
1071                                                 }
1072                                         } else {
1073                                                 transaction.commit();
1074                                                 localSession.close();
1075                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1076                                                 return;
1077                                         }
1078                                 } else {
1079                                         app = (EPApp) localSession.get(EPApp.class, appId);
1080                                         if (app == null || app.getId() == null) {
1081                                                 // App is already deleted!
1082                                                 transaction.commit();
1083                                                 localSession.close();
1084                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1085                                                 return;
1086                                         }
1087                                 }
1088                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1089                                 createAppFromOnboarding(app, onboardingApp, localSession);
1090                                 logger.debug(EELFLoggerDelegate.debugLogger,
1091                                                 "LR: updateApp: finished calling createAppFromOnboarding");
1092                                 localSession.saveOrUpdate(app);
1093                                 logger.debug(EELFLoggerDelegate.debugLogger,
1094                                                 "LR: updateApp: finished calling localSession.saveOrUpdate");
1095                                 // Enable or disable all menu items associated with this app
1096                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1097                                 logger.debug(EELFLoggerDelegate.debugLogger,
1098                                                 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1099                                 transaction.commit();
1100                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1101                                 epUebHelper.addPublisher(app);
1102                                 logger.debug(EELFLoggerDelegate.debugLogger,
1103                                                 "LR: updateApp: finished calling epUebHelper.addPublisher");
1104                                 result = true;
1105                         } catch (Exception e) {
1106                                 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1107                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1108                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1109                                 EcompPortalUtils.rollbackTransaction(transaction,
1110                                                 "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e));
1111                         } finally {
1112                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1113                         }
1114                         if (!result) {
1115                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1116                         }
1117                 }
1118
1119         }
1120
1121         public CambriaTopicManager getTopicManager(LinkedList<String> urlList, String key, String secret)
1122                         throws GeneralSecurityException, Exception {
1123                 throw new Exception("This method can only be invoked from child class");
1124         }
1125
1126         /**
1127          * Populates a transport model of the application from a database row model.
1128          * Leaves out the thumbnail because the FE fetches images via a different
1129          * API.
1130          * 
1131          * @param app
1132          *            Model of database row
1133          * @param onboardingApp
1134          *            Model for transport as JSON
1135          */
1136         @Override
1137         public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1138                 onboardingApp.id = app.getId();
1139                 onboardingApp.name = app.getName();
1140                 onboardingApp.imageUrl = app.getImageUrl();
1141                 onboardingApp.description = app.getDescription();
1142                 onboardingApp.notes = app.getNotes();
1143                 onboardingApp.url = app.getUrl();
1144                 onboardingApp.alternateUrl = app.getAlternateUrl();
1145                 onboardingApp.restUrl = app.getAppRestEndpoint();
1146                 onboardingApp.isOpen = app.getOpen();
1147                 onboardingApp.isEnabled = app.getEnabled();
1148                 onboardingApp.username = app.getUsername();
1149                 onboardingApp.appPassword = decryptedPassword(app.getAppPassword(), app);
1150                 onboardingApp.uebTopicName = app.getUebTopicName();
1151                 onboardingApp.uebKey = app.getUebKey();
1152                 onboardingApp.uebSecret = app.getUebSecret();
1153                 onboardingApp.isCentralAuth = app.getCentralAuth();
1154                 onboardingApp.nameSpace = app.getNameSpace();
1155                 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1156                 // if (app.getThumbnail() != null)
1157                 // onboardingApp.thumbnail = new
1158                 // String(Base64.getEncoder().encode(app.getThumbnail()));
1159         }
1160
1161         /**
1162          * Creates a database object for an application from an uploaded transport
1163          * model. Must decode the thumbnail, if any.
1164          * 
1165          * @param app
1166          * @param onboardingApp
1167          * @param localSession
1168          * @return The first argument.
1169          */
1170         protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1171                 app.setName(onboardingApp.name);
1172                 app.setDescription(onboardingApp.description);
1173                 app.setNotes(onboardingApp.notes);
1174                 app.setUrl(onboardingApp.url);
1175                 app.setAlternateUrl(onboardingApp.alternateUrl);
1176                 app.setAppRestEndpoint(onboardingApp.restUrl);
1177                 app.setOpen(onboardingApp.isOpen);
1178                 app.setEnabled(onboardingApp.isEnabled);
1179                 app.setUsername(onboardingApp.username);
1180                 app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
1181                 app.setUebTopicName(onboardingApp.uebTopicName);
1182                 app.setUebKey(onboardingApp.uebKey);
1183                 app.setUebSecret(onboardingApp.uebSecret);
1184                 app.setCentralAuth(onboardingApp.isCentralAuth);
1185                 app.setNameSpace(onboardingApp.nameSpace);
1186                 app.setRestrictedApp(onboardingApp.restrictedApp);
1187                 if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
1188                         logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1189                         String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
1190                         logger.debug(EELFLoggerDelegate.debugLogger,
1191                                         "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1192                         if (splitBase64Thumbnail.length > 1) {
1193                                 // This occurs when we have a new image, not an existing image
1194                                 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1195                                 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1196                                 // This is basically a boolean indicator that an image is
1197                                 // present.
1198                                 app.setImageUrl(constructImageName(onboardingApp));
1199                                 app.setThumbnail(decodedImage);
1200                         }
1201                 } else if (app.getThumbnail() != null && onboardingApp.imageLink == null) {
1202                         // The thumbnail that came in from the json is empty; the previous
1203                         // thumbnail is NOT empty. Must delete it.
1204                         logger.debug(EELFLoggerDelegate.debugLogger,
1205                                         "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1206                         app.setImageUrl(null);
1207                         app.setThumbnail(null);
1208                 } else {
1209                         logger.debug(EELFLoggerDelegate.debugLogger,
1210                                         "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1211                 }
1212                 return app;
1213         }
1214
1215         protected String constructImageName(OnboardingApp onboardingApp) {
1216                 return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
1217                                 + ".png";
1218         }
1219
1220         // Don't encrypt or decrypt the password if it is null or the empty string
1221         private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1222                 String result = "";
1223                 if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) {
1224                         try {
1225                                 result = CipherUtil.decrypt(encryptedAppPwd,
1226                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1227                         } catch (Exception e) {
1228                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1229                         }
1230                 }
1231                 return result;
1232         }
1233
1234         protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1235                 String result = "";
1236                 if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) {
1237                         try {
1238                                 result = CipherUtil.encrypt(decryptedAppPwd,
1239                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1240                         } catch (Exception e) {
1241                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1242                         }
1243                 }
1244                 return result;
1245         }
1246
1247         @SuppressWarnings("unchecked")
1248         @Override
1249         public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1250                 FieldsValidator fieldsValidator = new FieldsValidator();
1251                 final Map<String, Long> params = new HashMap<>();
1252                 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1253
1254                 try {
1255                         params.put("userId", user.getId());
1256                         epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1257                         Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1258                         for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1259                                 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1260                         }
1261                         for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1262                                 if (epWidgetsManPref.getWidgetid() != null) {
1263                                         Long widgetid = epWidgetsManPref.getWidgetid();
1264                                         if (existingWidgetsIds.containsKey(widgetid)) {
1265                                                 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1266                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1267                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1268                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1269                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1270                                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1271                                                 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1272                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1273                                         } else {
1274                                                 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1275                                                 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1276                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1277                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1278                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1279                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1280                                                 epWidgetsManualSort.setUserId(Ints.checkedCast(user.getId()));
1281                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1282                                         }
1283                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1284                                 }
1285                         }
1286                 } catch (Exception e) {
1287                         logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1288                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1289                 }
1290                 return fieldsValidator;
1291         }
1292
1293         @SuppressWarnings("unchecked")
1294         @Override
1295         public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1296                 FieldsValidator fieldsValidator = new FieldsValidator();
1297                 final Map<String, Long> params = new HashMap<>();
1298                 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1299                 try {
1300                         params.put("userId", user.getId());
1301                         epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1302                         Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1303                         for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1304                                 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1305                         }
1306                         for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1307                                 if (delEpWidgetsManPref.getWidgetid() != null) {
1308                                         Long widgetId = delEpWidgetsManPref.getWidgetid();
1309                                         if (existingWidgetIds.containsKey(widgetId)) {
1310                                                 dataAccessService.deleteDomainObjects(EPWidgetsManualSortPreference.class,
1311                                                                 "widget_id=" + widgetId + " AND user_id=" + user.getId(), null);
1312                                         }
1313                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1314                                 }
1315                         }
1316                 } catch (Exception e) {
1317                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1318                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1319                 }
1320                 return fieldsValidator;
1321         }
1322
1323         /*
1324          * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1325          *
1326          * @param: appsSortManual--contains User Apps Data
1327          *
1328          * @param: user--contains LoggedIn User Data
1329          */
1330         @SuppressWarnings("unchecked")
1331         @Override
1332         public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1333                 FieldsValidator fieldsValidator = new FieldsValidator();
1334                 final Map<String, Long> params = new HashMap<>();
1335                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1336
1337                 try {
1338                         params.put("userId", user.getId());
1339                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1340                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1341                         for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1342                                 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1343                         }
1344                         for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1345                                 if (epAppsManPref.getAppid() != null) {
1346                                         Long appid = epAppsManPref.getAppid();
1347                                         if (existingAppIds.containsKey(appid)) {
1348                                                 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1349                                                 epAppsManualSort
1350                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1351                                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1352                                                 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1353                                                 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1354                                         } else {
1355                                                 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1356                                                 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1357                                                 epAppsManualSort
1358                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1359                                                 epAppsManualSort.setUserId(Ints.checkedCast(user.getId()));
1360                                                 dataAccessService.saveDomainObject(epAppsManualSort, null);
1361                                         }
1362                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1363                                 }
1364                         }
1365                 } catch (Exception e) {
1366                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1367                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1368                 }
1369                 return fieldsValidator;
1370         }
1371
1372         /*
1373          * (non-Javadoc)
1374          *
1375          * @see org.openecomp.portalapp.portal.service.EPAppService#
1376          * deleteUserAppSortManual(java.lang.String,
1377          * org.openecomp.portalapp.portal.domain.EPUser)
1378          */
1379         @SuppressWarnings("unchecked")
1380         @Override
1381         public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1382                 FieldsValidator fieldsValidator = new FieldsValidator();
1383                 final Map<String, Long> params = new HashMap<>();
1384                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1385                 try {
1386                         params.put("userId", user.getId());
1387                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1388                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1389                         for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1390                                 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1391                         }
1392                         if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1393                                 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1394                                                 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1395                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1396                         }
1397                 } catch (Exception e) {
1398                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1399                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1400                 }
1401                 return fieldsValidator;
1402         }
1403
1404         @SuppressWarnings("unchecked")
1405         @Override
1406         public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1407                 FieldsValidator fieldsValidator = new FieldsValidator();
1408                 final Map<String, Long> params = new HashMap<>();
1409                 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1410                 EPUserAppsSortPreference usrSortPr = null;
1411                 try {
1412                         params.put("userId", user.getId());
1413                         epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1414                         if (epSortTypes.size() == 0) {
1415                                 usrSortPr = new EPUserAppsSortPreference();
1416                                 usrSortPr.setUserId(Ints.checkedCast(user.getId()));
1417                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1418                                 dataAccessService.saveDomainObject(usrSortPr, null);
1419                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1420                         } else {
1421                                 usrSortPr = epSortTypes.get(0);
1422                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1423                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1424                                 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1425                                 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1426                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1427                         }
1428                 } catch (Exception e) {
1429                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1430                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1431                 }
1432                 return fieldsValidator;
1433         }
1434
1435         @SuppressWarnings("unchecked")
1436         @Override
1437         public String getUserAppsSortTypePreference(EPUser user) {
1438                 final Map<String, Long> params = new HashMap<>();
1439                 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1440                 try {
1441                         params.put("userId", user.getId());
1442                         userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1443                         if (userSortPrefs.size() > 0)
1444                                 return userSortPrefs.get(0).getSortPref();
1445                         else
1446                                 return null;
1447                 } catch (Exception e) {
1448                         logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1449                 }
1450                 return null;
1451
1452         }
1453
1454         @Override
1455         public List<EPApp> getUserRemoteApps(String id) {
1456                 throw new RuntimeException(" Cannot be called from parent class");
1457         }
1458         
1459         @Override
1460         public UserRoles getUserProfileForLeftMenu(String loginId) {
1461                 final Map<String, String> params = new HashMap<>();
1462                 params.put("org_user_id", loginId);
1463                 @SuppressWarnings("unchecked")
1464                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1465                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1466                 if (usersRolesList == null || usersRolesList.size() < 1)
1467                         return null;
1468
1469                 return usersRolesList.get(0);
1470         }
1471         
1472         
1473         @Override
1474         public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1475                 // Check database.
1476                 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1477                 // If no roles are defined, treat this user as a guest.
1478                 if (user.isGuest() || userAndRoles == null) {
1479                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1480                                         user.getLoginId());
1481                         UserRole userRole = new UserRole();
1482                         userRole.setUser_Id(user.getId());
1483                         userRole.setOrgUserId(user.getLoginId());
1484                         userRole.setFirstName(user.getFirstName());
1485                         userRole.setLastName(user.getLastName());
1486                         userRole.setRoleId(-1L);
1487                         userRole.setRoleName("Guest");
1488                         userRole.setUser_Id(-1L);
1489                         userAndRoles = new UserRoles(userRole);
1490                 }
1491
1492                 return userAndRoles;
1493         }
1494         
1495
1496 }