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