24572fb2fc13a906ebdab215a1464f1b154b7734
[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  * 
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 import java.util.UUID;
51
52 import javax.annotation.PostConstruct;
53 import javax.servlet.http.HttpServletResponse;
54
55 import org.apache.commons.lang.StringUtils;
56 import org.hibernate.Session;
57 import org.hibernate.SessionFactory;
58 import org.hibernate.Transaction;
59 import org.hibernate.criterion.Criterion;
60 import org.hibernate.criterion.Restrictions;
61 import org.onap.portalapp.portal.domain.AdminUserApp;
62 import org.onap.portalapp.portal.domain.AdminUserApplications;
63 import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel;
64 import org.onap.portalapp.portal.domain.AppsResponse;
65 import org.onap.portalapp.portal.domain.EPApp;
66 import org.onap.portalapp.portal.domain.EPUser;
67 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
68 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
69 import org.onap.portalapp.portal.domain.EPUserAppsManualSortPreference;
70 import org.onap.portalapp.portal.domain.EPUserAppsSortPreference;
71 import org.onap.portalapp.portal.domain.EPWidgetsManualSortPreference;
72 import org.onap.portalapp.portal.domain.EcompApp;
73 import org.onap.portalapp.portal.domain.UserRole;
74 import org.onap.portalapp.portal.domain.UserRoles;
75 import org.onap.portalapp.portal.ecomp.model.AppCatalogItem;
76 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
77 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
78 import org.onap.portalapp.portal.transport.EPAppsManualPreference;
79 import org.onap.portalapp.portal.transport.EPAppsSortPreference;
80 import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref;
81 import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
82 import org.onap.portalapp.portal.transport.FieldsValidator;
83 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
84 import org.onap.portalapp.portal.transport.LocalRole;
85 import org.onap.portalapp.portal.transport.OnboardingApp;
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
123         @PostConstruct
124         private void init() {
125                 SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
126                 ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
127                 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
128                 RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
129         }
130
131         @Override
132         public List<EPApp> getUserAsAdminApps(EPUser user) {
133                 if (adminRolesService.isAccountAdmin(user)) {
134                         String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
135                                         + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
136                                         + " AND FN_APP.ENABLED = 'Y'";
137                         logQuery(sql);
138                         try {
139                                 @SuppressWarnings("unchecked")
140                                 List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
141                                 return adminApps;
142                         } catch (Exception e) {
143                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
144                                 return null;
145                         }
146                 } else {
147                         logger.error(EELFLoggerDelegate.errorLogger,
148                                         "getUserAsAdminApps: only Account Admin may invoke this function!");
149                         return new ArrayList<EPApp>();
150                 }
151         }
152
153         @Override
154         public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
155                 String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
156                                 + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
157                                 + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
158                                 + " AND FN_APP.ENABLED = 'Y'";
159
160                 String sql = String.format(format, orgUserId);
161                 logQuery(sql);
162
163                 try {
164                         @SuppressWarnings("unchecked")
165                         List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
166                         return adminApps;
167                 } catch (Exception e) {
168                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
169                         return null;
170                 }
171         }
172
173         @Override
174         public List<EPApp> getAppsFullList() {
175                 @SuppressWarnings("unchecked")
176                 List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
177                 return apps;
178         }
179
180         @Override
181         public List<EcompApp> getEcompAppAppsFullList() {
182                 return transformAppsToEcompApps(getAppsFullList());
183         }
184
185         @Override
186         public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
187                 List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
188                 for (EPApp app : appsList) {
189                         EcompApp ecompApp = new EcompApp();
190                         ecompApp.setId(app.getId());
191                         ecompApp.setName(app.getName());
192                         ecompApp.setImageUrl(app.getImageUrl());
193                         ecompApp.setDescription(app.getDescription());
194                         ecompApp.setNotes(app.getNotes());
195                         ecompApp.setUrl(app.getUrl());
196                         ecompApp.setAlternateUrl(app.getAlternateUrl());
197                         ecompApp.setUebTopicName(app.getUebTopicName());
198                         ecompApp.setUebKey(app.getUebKey());
199                         ecompApp.setUebSecret(app.getUebSecret());
200                         ecompApp.setEnabled(app.getEnabled());
201                         ecompApp.setCentralAuth(app.getCentralAuth());
202                         ecompApp.setNameSpace(app.getNameSpace());
203                         ecompApp.setRestrictedApp(app.isRestrictedApp());
204                         ecompAppList.add(ecompApp);
205                 }
206                 return ecompAppList;
207         }
208
209         @Override
210         public EPApp getApp(Long appId) {
211                 try {
212                         return (EPApp) dataAccessService.getDomainObject(EPApp.class, appId, null);
213                 } catch (Exception e) {
214                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
215                         return null;
216                 }
217         }
218
219         @SuppressWarnings("unchecked")
220         @Override
221         public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
222                 if (adminRolesService.isAccountAdmin(user)) {
223                         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 "
224                                         + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
225                                         + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
226                         String sql = String.format(format, user.getId());
227                         // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
228                         // app.APP_REST_ENDPOINT <> ''";
229                         logQuery(sql);
230                         try {
231                                 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
232                         } catch (Exception e) {
233                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
234                                 logger.error(EELFLoggerDelegate.errorLogger,
235                                                 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
236                         }
237                 }
238                 return new ArrayList<AppIdAndNameTransportModel>();
239         }
240
241         @Override
242         public EPApp getAppDetail(String appName) {
243                 final Map<String, String> params = new HashMap<String, String>();
244                 try {
245                         params.put("appName", appName);
246                         @SuppressWarnings("unchecked")
247                         List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null);
248                         return (apps.size() > 0) ? apps.get(0) : null;
249                 } catch(Exception e) {
250                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
251                         return null;
252                 }
253         }
254         
255         @Override
256         public EPApp getAppDetailByAppName(String appName) {
257                 final Map<String, String> params = new HashMap<String, String>();
258                 try {
259                         params.put("appName", appName);
260                         @SuppressWarnings("unchecked")
261                         List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getAppDetailsByAppName", params, null);
262                         if (apps.size() > 0) {
263                                 EPApp app = apps.get(0);
264                                 if (!EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
265                                         app.setCentralAuth(false);
266                                 }
267                                 return app;
268                         } else{
269                                 return null;
270                         }
271                 } catch (Exception e) {
272                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
273                         return null;
274                 }
275         }
276
277         @SuppressWarnings("unchecked")
278         @Override
279         public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
280                 if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
281                         String format = "";
282                         String sql = "";
283                         if (adminRolesService.isSuperAdmin(user)) {
284                                 format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
285                                                 + "where app.ENABLED = 'Y' AND app.app_type = 1";
286                         } else {
287                                 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 "
288                                                 + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
289                                                 + " AND app.ENABLED = 'Y' AND app.app_type = 1";
290                         }
291                         sql = String.format(format, user.getId());
292                         // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
293                         // app.APP_REST_ENDPOINT <> ''";
294                         logQuery(sql);
295                         try {
296                                 return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
297                         } catch (Exception e) {
298                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
299                                 logger.error(EELFLoggerDelegate.errorLogger,
300                                                 "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
301                         }
302                 }
303                 return new ArrayList<AppIdAndNameTransportModel>();
304         }
305
306         protected void logQuery(String sql) {
307                 logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
308         }
309
310         public DataAccessService getDataAccessService() {
311                 return dataAccessService;
312         }
313
314         public void setDataAccessService(DataAccessService dataAccessService) {
315                 this.dataAccessService = dataAccessService;
316         }
317
318         @SuppressWarnings("unchecked")
319         @Override
320         public List<AdminUserApplications> getAppsAdmins() {
321                 try {
322                         Map<String, String> params = new HashMap<>();
323                         params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID);
324                         List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins",
325                                         params, null);
326                         return aggregateRowsResultsByUserId(adminApps);
327                 } catch (Exception e) {
328                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
329                         return null;
330                 }
331         }
332
333         private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
334                 HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
335                 for (AdminUserApp app : adminApps) {
336                         Long userId = app.getUser_Id();
337                         if (adminUserApplications.get(userId) == null)
338                                 adminUserApplications.put(userId, new AdminUserApplications(app));
339                         else
340                                 adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
341                 }
342                 return new ArrayList<AdminUserApplications>(adminUserApplications.values());
343         }
344
345         @Override
346         public List<AppsResponse> getAllApps(Boolean all) {
347                 // If all is true, return both active and inactive apps. Otherwise, just
348                 // active apps.
349                 @SuppressWarnings("unchecked")
350                 // Sort the list by application name so the drop-down looks pretty.
351                 List<EPApp> apps = all
352                                 ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
353                                 : (List<EPApp>) dataAccessService.getList(EPApp.class,
354                                                 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
355
356                 List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
357                 for (EPApp app : apps) {
358                         appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
359                 }
360                 return appsModified;
361         }
362
363         @Override
364         public UserRoles getUserProfile(String loginId) {
365                 final Map<String, String> params = new HashMap<>();
366                 params.put("org_user_id", loginId);
367                 @SuppressWarnings("unchecked")
368                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null);
369                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
370                 if (usersRolesList == null || usersRolesList.size() < 1)
371                         return null;
372
373                 return usersRolesList.get(0);
374         }
375
376         @Override
377         public UserRoles getUserProfileNormalized(EPUser user) {
378                 // Check database.
379                 UserRoles userAndRoles = getUserProfile(user.getLoginId());
380                 // If no roles are defined, treat this user as a guest.
381                 if (user.isGuest() || userAndRoles == null) {
382                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
383                                         user.getLoginId());
384                         UserRole userRole = new UserRole();
385                         userRole.setUser_Id(user.getId());
386                         userRole.setOrgUserId(user.getLoginId());
387                         userRole.setFirstName(user.getFirstName());
388                         userRole.setLastName(user.getLastName());
389                         userRole.setRoleId(-1L);
390                         userRole.setRoleName("Guest");
391                         userRole.setUser_Id(-1L);
392                         userAndRoles = new UserRoles(userRole);
393                 }
394
395                 return userAndRoles;
396         }
397
398         protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
399                 HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
400                 for (UserRole user : userRoleList) {
401                         String orgUserId = user.getOrgUserId();
402                         if (userRoles.get(orgUserId) == null)
403                                 userRoles.put(orgUserId, new UserRoles(user));
404                         else
405                                 userRoles.get(orgUserId).addRole(user.getRoleName());
406                 }
407                 return new ArrayList<UserRoles>(userRoles.values());
408         }
409
410         private boolean isRestrictedApp(Long appId) {
411                 EPApp app = getApp(appId);
412                 return app.isRestrictedApp();
413         }
414
415         // For the functional menu edit
416         @Override
417         public List<LocalRole> getAppRoles(Long appId) {
418                 String sql = "";
419                 if (isRestrictedApp(appId)) {
420                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
421                 }else if(appId == 1){
422                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL";
423                 }else{
424                         sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'";
425                 }
426                 logQuery(sql);
427                 @SuppressWarnings("unchecked")
428                 List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
429                 return appRoles;
430         }
431
432         protected String userAppsQuery(EPUser user) {
433                 StringBuilder query = new StringBuilder();
434                 if (adminRolesService.isSuperAdmin(user)) {
435                         query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
436                 } else {
437                         query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
438                         query.append(
439                                         "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
440                         query.append(" AND FN_APP.ENABLED = 'Y'");
441                 }
442                 return query.toString();
443         }
444
445         protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
446                 FieldsValidator fieldsValidator = new FieldsValidator();
447                 if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
448                                 || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
449                                 || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
450                                 || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID))
451                                 // For a normal app (appType==1), these fields must be filled
452                                 // in.
453                                 // For a restricted app (appType==2), they will be empty.
454                                 || ((!onboardingApp.restrictedApp)
455                                                 && (onboardingApp.username == null || onboardingApp.username.length() == 0
456                                                                 || onboardingApp.appPassword == null || onboardingApp.appPassword.length() == 0))) {
457                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
458                 }
459                 return fieldsValidator;
460         }
461
462         @Override
463         public List<EPApp> getUserApps(EPUser user) {
464                 List<EPApp> openApps = getOpenApps();
465
466                 if (user.isGuest()) {
467                         return openApps;
468                 } else {
469                         String sql = userAppsQuery(user);
470                         logQuery(sql);
471
472                         // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
473                         List<EPApp> appsList = new ArrayList<>();
474                         @SuppressWarnings("unchecked")
475                         List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
476                         HashSet<EPApp> appSet = new HashSet<>();
477                         for (EPApp app : adminApps) {
478                                 appSet.add(app);
479                                 appsList.add(app);
480                         }
481
482                         for (EPApp app : openApps) {
483                                 if (!appSet.contains(app))
484                                         appsList.add(app);
485                         }
486
487                         return appsList;
488                 }
489         }
490
491         @Override
492         public List<EPApp> getPersAdminApps(EPUser user) {
493                 final Map<String, Long> params = new HashMap<>();
494                 params.put("userId", user.getId());
495                 // Named query is stored in EP.hbm.xml, mapped to EPApp
496                 @SuppressWarnings("unchecked")
497                 List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
498                 return list;
499         }
500
501         @Override
502         public List<EPApp> getPersUserApps(EPUser user) {
503                 final Map<String, Long> params = new HashMap<>();
504                 params.put("userId", user.getId());
505                 // Named query is stored in EP.hbm.xml, mapped to EPApp
506                 @SuppressWarnings("unchecked")
507                 List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
508                 return list;
509         }
510
511         /*
512          * (non-Javadoc)
513          *
514          * @see
515          * org.onap.portalapp.portal.service.EPAppService#getAppCatalog(
516          * org.onap.portalapp.portal.domain.EPUser)
517          */
518         @Override
519         public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
520                 final Map<String, Long> params = new HashMap<>();
521                 params.put("userId", user.getId());
522                 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
523                 @SuppressWarnings("unchecked")
524                 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
525                 return list;
526         }
527
528         /*
529          * (non-Javadoc)
530          *
531          * @see
532          * org.onap.portalapp.portal.service.EPAppService#getAdminAppCatalog(
533          * org.onap.portalapp.portal.domain.EPUser)
534          */
535         @Override
536         public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
537                 final Map<String, Long> params = new HashMap<>();
538                 params.put("userId", user.getId());
539                 // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
540                 @SuppressWarnings("unchecked")
541                 List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
542                 return list;
543         }
544
545         private List<EPApp> getOpenApps() {
546                 @SuppressWarnings("unchecked")
547                 List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
548                 return openApps;
549         }
550
551         @SuppressWarnings("unchecked")
552         @Override
553         public List<EPApp> getAppsOrderByName(EPUser user) {
554                 final Map<String, Long> params = new HashMap<>();
555                 List<EPApp> sortedAppsByName = null;
556                 try {
557                         if (adminRolesService.isSuperAdmin(user)) {
558                                 params.put("userId", user.getId());
559                                 sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
560                         } else {
561                                 params.put("userId", user.getId());
562                                 sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
563                         }
564                 } catch (Exception e) {
565                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
566                 }
567                 return sortedAppsByName;
568         }
569
570         @SuppressWarnings("unchecked")
571         @Override
572         public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
573
574                 final Map<String, Long> params = new HashMap<>();
575                 List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
576                 List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
577                 try {
578                         if (adminRolesService.isSuperAdmin(user)) {
579                                 params.put("userId", user.getId());
580                                 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
581                         } else {
582                                 params.put("userId", user.getId());
583                                 sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
584                         }
585                         Set<String> epAppSet = new HashSet<String>();
586                         for (EPApp eapp : sortedAppsByLastUsed)
587                                 if (!epAppSet.contains(eapp.getName())) {
588                                         finalsortedAppsByLastUsed.add(eapp);
589                                         epAppSet.add(eapp.getName());
590                                 }
591
592                 } catch (Exception e) {
593                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
594                 }
595                 return finalsortedAppsByLastUsed;
596         }
597
598         @SuppressWarnings("unchecked")
599         @Override
600         public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
601                 final Map<String, Long> params = new HashMap<>();
602                 List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
603                 List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
604                 try {
605                         if (adminRolesService.isSuperAdmin(user)) {
606                                 params.put("userId", user.getId());
607                                 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
608                         } else {
609                                 params.put("userId", user.getId());
610                                 sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
611                         }
612                         Set<String> epAppSet = new HashSet<String>();
613
614                         for (EPApp eapp : sortedAppsByMostUsed) {
615                                 if (!epAppSet.contains(eapp.getName())) {
616                                         finalsortedAppsByMostUsed.add(eapp);
617                                         epAppSet.add(eapp.getName());
618                                 }
619                         }
620                 } catch (Exception e) {
621                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
622                 }
623
624                 return finalsortedAppsByMostUsed;
625         }
626
627         /*
628          * This Method retrieves the User Apps by Sort Manual Preference
629          *
630          * @param: user--contains LoggedIn User Data
631          */
632         @SuppressWarnings("unchecked")
633         @Override
634         public List<EPApp> getAppsOrderByManual(EPUser user) {
635                 final Map<String, Long> params = new HashMap<>();
636                 List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
637                 List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
638                 try {
639                         if (adminRolesService.isSuperAdmin(user)) {
640                                 params.put("userId", user.getId());
641                                 sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
642                         } else {
643                                 params.put("userId", user.getId());
644                                 sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
645                         }
646                         Set<String> epAppSet = new HashSet<String>();
647
648                         for (EPApp eapp : sortedAppsByManual) {
649                                 if (!epAppSet.contains(eapp.getName())) {
650                                         finalsortedAppsByManual.add(eapp);
651                                         epAppSet.add(eapp.getName());
652                                 }
653                         }
654                 } catch (Exception e) {
655                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
656                 }
657                 return finalsortedAppsByManual;
658         }
659
660         @Override
661         public List<OnboardingApp> getOnboardingApps() {
662                 @SuppressWarnings("unchecked")
663                 List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
664                 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
665                 for (EPApp app : apps) {
666                         OnboardingApp onboardingApp = new OnboardingApp();
667                         app.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);//to hide password from get request
668                         createOnboardingFromApp(app, onboardingApp);
669                         onboardingAppsList.add(onboardingApp);
670                 }
671                 return onboardingAppsList;
672         }
673
674         @Override
675         public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
676                 @SuppressWarnings("unchecked")
677                 List<EPApp> apps = dataAccessService.getList(EPApp.class,
678                                 " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
679                 List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
680                 for (EPApp app : apps) {
681                         OnboardingApp onboardingApp = new OnboardingApp();
682                         app.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request
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
1070         protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1071                         EPUser user) {
1072                 synchronized (syncRests) {
1073                         boolean result = false;
1074                         Session localSession = null;
1075                         Transaction transaction = null;
1076                         try {
1077                                 localSession = sessionFactory.openSession();
1078                                 transaction = localSession.beginTransaction();
1079                                 EPApp app;
1080                                 if (appId == null) {
1081                                         app = new EPApp();
1082                                         /*
1083                                          * In the parent class, the UEB code is responsible for generating the
1084                                          * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1085                                          * may be used in future at which point we can just remove this method and
1086                                          * depend on parent class's method So, using UUID generator to generate the
1087                                          * unique key instead.
1088                                          */
1089                                         String uuidStr = UUID.randomUUID().toString();
1090                                         String appKey = uuidStr;
1091                                         String appSecret = uuidStr;
1092                                         String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1093                                         onboardingApp.setUebTopicName(appMailboxName);
1094                                         onboardingApp.setUebKey(appKey);
1095                                         onboardingApp.setUebSecret(appSecret);
1096                                 } else {
1097                                         app = (EPApp) localSession.get(EPApp.class, appId);
1098                                         if (app == null || app.getId() == null) {
1099                                                 // App is already deleted!
1100                                                 transaction.commit();
1101                                                 localSession.close();
1102                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1103                                                 return;
1104                                         }
1105                                 }
1106                                 logger.debug(EELFLoggerDelegate.debugLogger,
1107                                                 "updateRestrictedApp: about to call createAppFromOnboarding");
1108                                 createAppFromOnboarding(app, onboardingApp, localSession);
1109                                 logger.debug(EELFLoggerDelegate.debugLogger,
1110                                                 "updateRestrictedApp: finished calling createAppFromOnboarding");
1111                                 localSession.saveOrUpdate(app);
1112                                 logger.debug(EELFLoggerDelegate.debugLogger,
1113                                                 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1114                                 // Enable or disable all menu items associated with this app
1115                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1116                                 logger.debug(EELFLoggerDelegate.debugLogger,
1117                                                 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1118                                 transaction.commit();
1119                                 logger.debug(EELFLoggerDelegate.debugLogger,
1120                                                 "updateRestrictedApp: finished calling transaction.commit");
1121                                 result = true;
1122                         } catch (Exception e) {
1123                                 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1124                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1125                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1126                                 EcompPortalUtils.rollbackTransaction(transaction,
1127                                                 "updateRestrictedApp rollback, exception = " + e.toString());
1128                         } finally {
1129                                 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1130                         }
1131                         if (!result) {
1132                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1133                         }
1134                 }
1135
1136         }
1137
1138         @Deprecated
1139         protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1140                         EPUser user) {
1141                 synchronized (syncRests) {
1142                         boolean result = false;
1143                         Session localSession = null;
1144                         Transaction transaction = null;
1145                         try {
1146                                 localSession = sessionFactory.openSession();
1147                                 transaction = localSession.beginTransaction();
1148                                 EPApp app;
1149                                 if (appId == null) {
1150                                         app = new EPApp();
1151                                         // -------------------------------------------------------------------------------------------
1152                                         // Register this App with the UEB communication server.
1153                                         // Save
1154                                         // the App's unique mailbox/topic
1155                                         // name and keys to the FN_APP table. The App's mailbox
1156                                         // and
1157                                         // keys will be visible to the
1158                                         // admin on the ONAP portal.
1159                                         // -------------------------------------------------------------------------------------------
1160                                         TopicManager topicManager = new TopicManager() {
1161
1162                                                 EPAppCommonServiceImpl service;
1163
1164                                                 public void init(EPAppCommonServiceImpl _service) {
1165                                                         service = _service;
1166                                                 }
1167
1168                                                 public void createTopic(String key, String secret, String topicName,
1169                                                                 String topicDescription) throws HttpException, CambriaApiException, IOException {
1170
1171                                                         init(EPAppCommonServiceImpl.this);
1172                                                         final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1173                                                         if (logger.isInfoEnabled()) {
1174                                                                 logger.info("==> createTopic");
1175                                                                 logger.info("topicName: " + topicName);
1176                                                                 logger.info("topicDescription: " + topicDescription);
1177                                                         }
1178                                                         CambriaTopicManager tm = null;
1179                                                         try {
1180                                                                 tm = service.getTopicManager(urlList, key, secret);
1181                                                         } catch (Exception e) {
1182                                                                 logger.error("pub.build Exception ", e);
1183                                                                 throw new CambriaApiException(topicName);
1184                                                         }
1185                                                         tm.createTopic(topicName, topicDescription, 1, 1);
1186                                                 }
1187
1188                                                 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1189                                                                 String topicName) throws HttpException, CambriaApiException, IOException {
1190                                                         logger.info("==> addPublisher to topic " + topicName);
1191                                                         final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1192                                                         CambriaTopicManager tm = null;
1193                                                         try {
1194                                                                 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1195                                                         } catch (Exception e) {
1196                                                                 logger.error("pub.build Exception ", e);
1197                                                                 throw new CambriaApiException(topicName);
1198                                                         }
1199                                                         tm.allowProducer(topicName, publisherKey);
1200                                                 }
1201
1202                                         };
1203                                         final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1204                                                         .usingHosts(Helper.uebUrlList()).build();
1205                                         com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1206                                                         "ONAP Portal Owner");
1207                                         String appKey = credential.getApiKey();
1208                                         String appSecret = credential.getApiSecret();
1209                                         String appMailboxName = null;
1210
1211                                         int maxNumAttemptsToCreateATopic = 3;
1212                                         boolean successfullyCreatedMailbox = false;
1213                                         for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1214                                                 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1215
1216                                                 try {
1217                                                         topicManager.createTopic(
1218                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1219                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1220                                                                         appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
1221                                                         successfullyCreatedMailbox = true;
1222                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1223                                                                         "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
1224                                                         logger.debug(EELFLoggerDelegate.debugLogger, "    Key = " + appKey + " Secret = "
1225                                                                         + appSecret + " generated using = " + user.getEmail());
1226                                                         break;
1227                                                 } catch (HttpException e) {
1228                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1229                                                         if (e.getStatusCode() == 409) {
1230                                                                 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1231                                                                                 + " already exists. Will try using a different name", e);
1232                                                         } else {
1233                                                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1234                                                                                 e);
1235                                                         }
1236                                                 }
1237                                         }
1238
1239                                         if (successfullyCreatedMailbox) {
1240                                                 onboardingApp.setUebTopicName(appMailboxName);
1241                                                 onboardingApp.setUebKey(appKey);
1242                                                 onboardingApp.setUebSecret(appSecret);
1243
1244                                                 try {
1245                                                         /*
1246                                                          * EP is a publisher to this App's new mailbox
1247                                                          */
1248                                                         topicManager.addPublisher(
1249                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1250                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1251                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1252                                                                         appMailboxName);
1253
1254                                                         /*
1255                                                          * This App is a subscriber of its own mailbox
1256                                                          */
1257                                                         topicManager.addSubscriber(
1258                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1259                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1260                                                                         appMailboxName);
1261
1262                                                         /*
1263                                                          * This App is a publisher to EP
1264                                                          */
1265                                                         topicManager.addPublisher(
1266                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1267                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1268                                                                         PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1269                                                 } catch (HttpException | CambriaApiException | IOException e) {
1270                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1271                                                         logger.error(EELFLoggerDelegate.errorLogger,
1272                                                                         "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1273                                                         transaction.commit();
1274                                                         localSession.close();
1275                                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1276                                                         return;
1277                                                 }
1278                                         } else {
1279                                                 transaction.commit();
1280                                                 localSession.close();
1281                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1282                                                 return;
1283                                         }
1284                                 } else {
1285                                         app = (EPApp) localSession.get(EPApp.class, appId);
1286                                         if (app == null || app.getId() == null) {
1287                                                 // App is already deleted!
1288                                                 transaction.commit();
1289                                                 localSession.close();
1290                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1291                                                 return;
1292                                         }
1293                                 }
1294                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1295                                 createAppFromOnboarding(app, onboardingApp, localSession);
1296                                 logger.debug(EELFLoggerDelegate.debugLogger,
1297                                                 "LR: updateApp: finished calling createAppFromOnboarding");
1298                                 localSession.saveOrUpdate(app);
1299                                 logger.debug(EELFLoggerDelegate.debugLogger,
1300                                                 "LR: updateApp: finished calling localSession.saveOrUpdate");
1301                                 // Enable or disable all menu items associated with this app
1302                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
1303                                 logger.debug(EELFLoggerDelegate.debugLogger,
1304                                                 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1305                                 transaction.commit();
1306                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1307                                 logger.debug(EELFLoggerDelegate.debugLogger,
1308                                                 "LR: updateApp: finished calling epUebHelper.addPublisher");
1309                                 result = true;
1310                         } catch (Exception e) {
1311                                 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1312                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1313                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1314                                 EcompPortalUtils.rollbackTransaction(transaction,
1315                                                 "updateApp rollback, exception = " + e.toString());
1316                         } finally {
1317                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1318                         }
1319                         if (!result) {
1320                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1321                         }
1322                 }
1323
1324         }
1325
1326         public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1327                         throws GeneralSecurityException, Exception {
1328                 throw new Exception("This method can only be invoked from child class");
1329         }
1330
1331         /**
1332          * Populates a transport model of the application from a database row model.
1333          * Leaves out the thumbnail because the FE fetches images via a different
1334          * API.
1335          * 
1336          * @param app
1337          *            Model of database row
1338          * @param onboardingApp
1339          *            Model for transport as JSON
1340          */
1341         @Override
1342         public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1343                 onboardingApp.id = app.getId();
1344                 onboardingApp.name = app.getName();
1345                 onboardingApp.imageUrl = app.getImageUrl();
1346                 onboardingApp.description = app.getDescription();
1347                 onboardingApp.notes = app.getNotes();
1348                 onboardingApp.url = app.getUrl();
1349                 onboardingApp.alternateUrl = app.getAlternateUrl();
1350                 onboardingApp.restUrl = app.getAppRestEndpoint();
1351                 onboardingApp.isOpen = app.getOpen();
1352                 onboardingApp.isEnabled = app.getEnabled();
1353                 onboardingApp.username = app.getUsername();
1354                 onboardingApp.appPassword = (app.getAppPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) ? EPCommonSystemProperties.APP_DISPLAY_PASSWORD :decryptedPassword(app.getAppPassword(), app);
1355                 onboardingApp.uebTopicName = app.getUebTopicName();
1356                 onboardingApp.uebKey = app.getUebKey();
1357                 onboardingApp.uebSecret = app.getUebSecret();
1358                 onboardingApp.isCentralAuth = app.getCentralAuth();
1359                 onboardingApp.nameSpace = app.getNameSpace();
1360                 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1361                 // if (app.getThumbnail() != null)
1362                 // onboardingApp.thumbnail = new
1363                 // String(Base64.getEncoder().encode(app.getThumbnail()));
1364         }
1365
1366         /**
1367          * Creates a database object for an application from an uploaded transport
1368          * model. Must decode the thumbnail, if any.
1369          * 
1370          * @param app
1371          * @param onboardingApp
1372          * @param localSession
1373          * @return The first argument.
1374          */
1375         protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1376                 app.setName(onboardingApp.name);
1377                 app.setDescription(onboardingApp.description);
1378                 app.setNotes(onboardingApp.notes);
1379                 app.setUrl(onboardingApp.url);
1380                 app.setAlternateUrl(onboardingApp.alternateUrl);
1381                 app.setAppRestEndpoint(onboardingApp.restUrl);
1382                 app.setOpen(onboardingApp.isOpen);
1383                 app.setEnabled(onboardingApp.isEnabled);
1384                 app.setUsername(onboardingApp.username);
1385                 if(!onboardingApp.appPassword.equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1386                 app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
1387                 //app.setUebTopicName(onboardingApp.uebTopicName);
1388                 app.setUebKey(onboardingApp.uebKey);
1389                 app.setUebSecret(onboardingApp.uebSecret);
1390                 app.setCentralAuth(onboardingApp.isCentralAuth);
1391                 app.setNameSpace(onboardingApp.nameSpace);
1392                 app.setRestrictedApp(onboardingApp.restrictedApp);
1393                 if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
1394                         logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1395                         String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
1396                         logger.debug(EELFLoggerDelegate.debugLogger,
1397                                         "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1398                         if (splitBase64Thumbnail.length > 1) {
1399                                 // This occurs when we have a new image, not an existing image
1400                                 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1401                                 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1402                                 // This is basically a boolean indicator that an image is
1403                                 // present.
1404                                 app.setImageUrl(constructImageName(onboardingApp));
1405                                 app.setThumbnail(decodedImage);
1406                         }
1407                 } else if (app.getThumbnail() != null && onboardingApp.imageLink == null) {
1408                         // The thumbnail that came in from the json is empty; the previous
1409                         // thumbnail is NOT empty. Must delete it.
1410                         logger.debug(EELFLoggerDelegate.debugLogger,
1411                                         "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1412                         app.setImageUrl(null);
1413                         app.setThumbnail(null);
1414                 } else {
1415                         logger.debug(EELFLoggerDelegate.debugLogger,
1416                                         "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1417                 }
1418                 return app;
1419         }
1420
1421         protected String constructImageName(OnboardingApp onboardingApp) {
1422                 return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
1423                                 + ".png";
1424         }
1425
1426         // Don't encrypt or decrypt the password if it is null or the empty string
1427         private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1428                 String result = "";
1429                 if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) {
1430                         try {
1431                                 result = CipherUtil.decryptPKC(encryptedAppPwd,
1432                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1433                         } catch (Exception e) {
1434                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1435                         }
1436                 }
1437                 return result;
1438         }
1439
1440         protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1441                 String result = "";
1442                 if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) {
1443                         try {
1444                                 result = CipherUtil.encryptPKC(decryptedAppPwd,
1445                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
1446                         } catch (Exception e) {
1447                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1448                         }
1449                 }
1450                 return result;
1451         }
1452
1453         @SuppressWarnings("unchecked")
1454         @Override
1455         public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1456                 FieldsValidator fieldsValidator = new FieldsValidator();
1457                 final Map<String, Long> params = new HashMap<>();
1458                 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1459
1460                 try {
1461                         params.put("userId", user.getId());
1462                         epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1463                         Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1464                         for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1465                                 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1466                         }
1467                         for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1468                                 if (epWidgetsManPref.getWidgetid() != null) {
1469                                         Long widgetid = epWidgetsManPref.getWidgetid();
1470                                         if (existingWidgetsIds.containsKey(widgetid)) {
1471                                                 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1472                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1473                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1474                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1475                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1476                                                 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1477                                                 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1478                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1479                                         } else {
1480                                                 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1481                                                 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1482                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1483                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1484                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1485                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1486                                                 epWidgetsManualSort.setUserId(user.getId());
1487                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1488                                         }
1489                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1490                                 }
1491                         }
1492                 } catch (Exception e) {
1493                         logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1494                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1495                 }
1496                 return fieldsValidator;
1497         }
1498
1499         @SuppressWarnings("unchecked")
1500         @Override
1501         public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1502                 FieldsValidator fieldsValidator = new FieldsValidator();
1503                 final Map<String, Long> params = new HashMap<>();
1504                 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1505                 try {
1506                         params.put("userId", user.getId());
1507                         epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1508                         Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1509                         for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1510                                 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1511                         }
1512                         for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1513                                 if (delEpWidgetsManPref.getWidgetid() != null) {
1514                                         Long widgetId = delEpWidgetsManPref.getWidgetid();
1515                                         if (existingWidgetIds.containsKey(widgetId)) {
1516                                                 params.put("widgetId",widgetId);
1517                                                 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1518                                         }
1519                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1520                                 }
1521                         }
1522                 } catch (Exception e) {
1523                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1524                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1525                 }
1526                 return fieldsValidator;
1527         }
1528
1529         /*
1530          * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1531          *
1532          * @param: appsSortManual--contains User Apps Data
1533          *
1534          * @param: user--contains LoggedIn User Data
1535          */
1536         @SuppressWarnings("unchecked")
1537         @Override
1538         public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1539                 FieldsValidator fieldsValidator = new FieldsValidator();
1540                 final Map<String, Long> params = new HashMap<>();
1541                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1542
1543                 try {
1544                         params.put("userId", user.getId());
1545                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1546                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1547                         for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1548                                 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1549                         }
1550                         for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1551                                 if (epAppsManPref.getAppid() != null) {
1552                                         Long appid = epAppsManPref.getAppid();
1553                                         if (existingAppIds.containsKey(appid)) {
1554                                                 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1555                                                 epAppsManualSort
1556                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1557                                                 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1558                                                 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1559                                                 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1560                                         } else {
1561                                                 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1562                                                 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1563                                                 epAppsManualSort
1564                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1565                                                 epAppsManualSort.setUserId(user.getId());
1566                                                 dataAccessService.saveDomainObject(epAppsManualSort, null);
1567                                         }
1568                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1569                                 }
1570                         }
1571                 } catch (Exception e) {
1572                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1573                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1574                 }
1575                 return fieldsValidator;
1576         }
1577
1578         /*
1579          * (non-Javadoc)
1580          *
1581          * @see org.onap.portalapp.portal.service.EPAppService#
1582          * deleteUserAppSortManual(java.lang.String,
1583          * org.onap.portalapp.portal.domain.EPUser)
1584          */
1585         @SuppressWarnings("unchecked")
1586         @Override
1587         public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1588                 FieldsValidator fieldsValidator = new FieldsValidator();
1589                 final Map<String, Long> params = new HashMap<>();
1590                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1591                 try {
1592                         params.put("userId", user.getId());
1593                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1594                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1595                         for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1596                                 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1597                         }
1598                         if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1599                                 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1600                                                 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1601                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1602                         }
1603                 } catch (Exception e) {
1604                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1605                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1606                 }
1607                 return fieldsValidator;
1608         }
1609
1610         @SuppressWarnings("unchecked")
1611         @Override
1612         public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1613                 FieldsValidator fieldsValidator = new FieldsValidator();
1614                 final Map<String, Long> params = new HashMap<>();
1615                 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1616                 EPUserAppsSortPreference usrSortPr = null;
1617                 try {
1618                         params.put("userId", user.getId());
1619                         epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1620                         if (epSortTypes.size() == 0) {
1621                                 usrSortPr = new EPUserAppsSortPreference();
1622                                 usrSortPr.setUserId((int)(long)(user.getId()));
1623                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1624                                 dataAccessService.saveDomainObject(usrSortPr, null);
1625                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1626                         } else {
1627                                 usrSortPr = epSortTypes.get(0);
1628                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1629                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1630                                 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1631                                 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1632                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1633                         }
1634                 } catch (Exception e) {
1635                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1636                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1637                 }
1638                 return fieldsValidator;
1639         }
1640
1641         @SuppressWarnings("unchecked")
1642         @Override
1643         public String getUserAppsSortTypePreference(EPUser user) {
1644                 final Map<String, Long> params = new HashMap<>();
1645                 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1646                 try {
1647                         params.put("userId", user.getId());
1648                         userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1649                         if (userSortPrefs.size() > 0)
1650                                 return userSortPrefs.get(0).getSortPref();
1651                         else
1652                                 return null;
1653                 } catch (Exception e) {
1654                         logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1655                 }
1656                 return null;
1657
1658         }
1659
1660         @Override
1661         public List<EPApp> getUserRemoteApps(String id) {
1662                 throw new RuntimeException(" Cannot be called from parent class");
1663         }
1664         
1665         @Override
1666         public UserRoles getUserProfileForLeftMenu(String loginId) {
1667                 final Map<String, String> params = new HashMap<>();
1668                 params.put("org_user_id", loginId);
1669                 @SuppressWarnings("unchecked")
1670                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1671                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1672                 if (usersRolesList == null || usersRolesList.size() < 1)
1673                         return null;
1674
1675                 return usersRolesList.get(0);
1676         }
1677         
1678         
1679         @Override
1680         public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1681                 final Map<String, String> params = new HashMap<>();
1682                 params.put("org_user_id", loginId);
1683                 @SuppressWarnings("unchecked")
1684                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1685                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1686                 if (usersRolesList == null || usersRolesList.size() < 1)
1687                         return null;
1688
1689                 return usersRolesList.get(0);
1690         }
1691         
1692         @Override
1693         public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1694                 // Check database.
1695                 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1696                 // If no roles are defined, treat this user as a guest.
1697                 if (user.isGuest() || userAndRoles == null) {
1698                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1699                                         user.getLoginId());
1700                         userAndRoles = createUserRoles(user);
1701                 }
1702
1703                 return userAndRoles;
1704         }
1705         
1706         @Override
1707         public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1708                 // Check database.
1709                 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1710                 // If no roles are defined, treat this user as a guest.
1711                 if (user.isGuest() || userAndRoles == null) {
1712                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1713                                         user.getLoginId());
1714                         userAndRoles = createUserRoles(user);
1715                 }
1716
1717                 return userAndRoles;
1718         }
1719
1720         
1721         public UserRoles createUserRoles(EPUser user)
1722         {
1723                 UserRole userRole = new UserRole();
1724                 userRole.setUser_Id(user.getId());
1725                 userRole.setOrgUserId(user.getLoginId());
1726                 userRole.setFirstName(user.getFirstName());
1727                 userRole.setLastName(user.getLastName());
1728                 userRole.setRoleId(-1L);
1729                 userRole.setRoleName("Guest");
1730                 userRole.setUser_Id(-1L);
1731                 UserRoles userAndRoles = new UserRoles(userRole);
1732                 return userAndRoles;
1733                 
1734         }
1735 }