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