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