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