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