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