App Onboarding Inactive -500 Internal Server Error
[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                         } else {
947                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
948                         }
949                 }
950                 return fieldsValidator;
951         }
952
953         @Override
954         public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
955                 FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
956                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
957                         validateOnboardingApp(newOnboardingApp, fieldsValidator);
958                 }
959                 if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
960                         if (newOnboardingApp.getId() == null) {
961                                 updateApp(null, newOnboardingApp, fieldsValidator, user);
962                         } else {
963                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
964                         }
965                 }
966                 return fieldsValidator;
967         }
968
969         @SuppressWarnings("unchecked")
970         @Override
971         public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
972                 FieldsValidator fieldsValidator = new FieldsValidator();
973                 if (!adminRolesService.isSuperAdmin(user)) {
974                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
975                         return fieldsValidator;
976                 }
977                 final Map<String, Long> params = new HashMap<>();
978                 params.put("app_id", appid);
979                 
980                 //Checking if App is associated with any exiting microservices- ep_microservice:
981                 final Map<String, Long> queryparams = new HashMap<>();
982                 queryparams.put("applicationId", appid);
983                 List<MicroserviceData> microservicesList  = dataAccessService.executeNamedQuery( "getMicroservicesByAppId", queryparams, null);
984                 if(microservicesList!=null && microservicesList.size()>0) {
985                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
986                         return fieldsValidator;
987                 }
988                 
989                 List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>();
990                 EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null);
991             for(int i=0;i<EPUserAppRolesRequestList.size();i++)
992             {
993              dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null);
994                 
995             }
996             Session localSession = null;
997                 Transaction transaction = null;
998                 Boolean result = false;
999                 try {
1000                         localSession = sessionFactory.openSession();
1001                         transaction = localSession.beginTransaction();
1002                         
1003                         // 1) Remove the URL for any functional menu item associated with
1004                         // this app
1005                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting URL for any functional menu item associated with app");
1006                         // Named query is stored in EP.hbm.xml, mapped to EPApp
1007                          dataAccessService.executeNamedQuery("updateMenuFunctionalAndRoles", params, null);
1008                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp:  Deleted URL for any functional menu item associated with app");
1009
1010                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting favorites associated with a menu item that is associated with this app");
1011                         // 2)Remove any favorites associated with a menu item that is
1012                         // associated with this app
1013                         dataAccessService.executeNamedQuery("removeAppFromMenuFavorites", params, null);
1014                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted favorites associated with a menu item that is associated with this app");
1015
1016                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting role, appid records from fn_menu_functional_role that are associated with this app");
1017                         // 3)Remove all role, appid records from fn_menu_functional_role
1018                         // that are associated with this app
1019                          dataAccessService.executeNamedQuery("removeAppFromMenuFunctionalRoles", params, null);
1020                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted role, appid records from fn_menu_functional_role that are associated with this app");
1021
1022                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1023                         // 4)Remove all roles, rolefunctions, appid records from ep_app_role_function
1024                         // that are associated with this app
1025                          dataAccessService.executeNamedQuery("removeAppFromEpAppRoleFunction", params, null);
1026                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all roles, rolefunctions, appid records from ep_app_role_function that are associated with this app");
1027                          
1028                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all rolefunctions, appid records from ep_app_function that are associated with this app");
1029                         // 5)Remove all rolefunctions, appid records from ep_app_function
1030                         // that are associated with this app
1031                          dataAccessService.executeNamedQuery("removeAppFromEpAppFunction", params, null);
1032                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp:  Deleted all rolefunctions, appid records from ep_app_function that are associated with this app");
1033          
1034                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_user_role associated with this app");
1035                         // 6)Remove all records from fn_user_role associated with this app
1036                          dataAccessService.executeNamedQuery("removeAppFromFnUserRole", params, null);
1037                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_user_role associated with this app");
1038                          
1039                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any widgets associated with this app");
1040                         // 7)Remove any widgets associated with this app
1041                          dataAccessService.executeNamedQuery("removeAppFromEpWidgetCatalogRole", params, null);
1042                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted widgets associated with this app");
1043                          
1044                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting any roles associated with this app");
1045                         // 8)Remove any roles associated with this app
1046                          dataAccessService.executeNamedQuery("removeAppFromEpRoleNotification", params, null);
1047                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted roles associated with this app");
1048                          
1049                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting all records from fn_role associated with this app");
1050                         // 9)Remove all records from fn_role associated with this app
1051                          dataAccessService.executeNamedQuery("removeAppFromFnRole", params, null);
1052                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted all records from fn_role associated with this app");
1053                         
1054                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting in table fn_app_contact_us entries associated with this app");
1055                          // 10)Remove app contact us entries
1056                          dataAccessService.executeNamedQuery("removeAppFromAppContactUs", params, null);
1057                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted in table fn_app_contact_us entries associated with this app");
1058
1059                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the fn_pers_user_app_sel table");
1060                         // 11)Remove rows in the app personalization selection table
1061                          dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppSel", params, null);
1062                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the fn_pers_user_app_sel table");
1063                          
1064                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_pers_user_app_man_sort table");
1065                         // 12)Remove rows in the app personalization sort table
1066                          dataAccessService.executeNamedQuery("removeAppFromEpPersUserAppManSort", params, null);
1067                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_pers_user_app_man_sort table");
1068                          
1069                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_user_roles_request table");
1070                         // 13)Remove rows in the app personalization sort table
1071                          dataAccessService.executeNamedQuery("removeAppFromEpUserRolesRequest", params, null);
1072                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_user_roles_request table");
1073                          
1074                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting rows in the ep_web_analytics_source");
1075                         // 14)Remove rows in the ep_web_analytics_source
1076                          dataAccessService.executeNamedQuery("removeAppFromEpWebAnalytics", params, null);
1077                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted rows in the ep_web_analytics_source");
1078                          
1079                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleting the app ");
1080                         // 15)Delete the app
1081                          dataAccessService.executeNamedQuery("removeAppFromFnApp", params, null);
1082                          logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp: Deleted the app");
1083                         
1084                         /*
1085                         // 1) Remove the URL for any functional menu item associated with
1086                         // this app
1087                         String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
1088                                         + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
1089                         logQuery(sql);
1090                         Query query = localSession.createSQLQuery(sql);
1091                         query.executeUpdate();
1092
1093                         // Remove any favorites associated with a menu item that is
1094                         // associated with this app
1095                         sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
1096                                         + " where fn_menu_functional_roles.app_id='" + appid + "' "
1097                                         + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
1098                         logQuery(sql);
1099                         query = localSession.createSQLQuery(sql);
1100                         query.executeUpdate();
1101
1102                         // Remove all role, appid records from fn_menu_functional_role
1103                         // that are associated with this app
1104                         sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
1105                         logQuery(sql);
1106                         query = localSession.createSQLQuery(sql);
1107                         query.executeUpdate();
1108                         
1109                         
1110                         // Remove all roles, rolefunctions, appid records from ep_app_role_function
1111                         // that are associated with this app
1112                     sql = "DELETE FROM ep_app_role_function WHERE app_id='" + appid + "'";
1113                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1114                          query = localSession.createSQLQuery(sql);
1115                         query.executeUpdate();
1116                         
1117                         //Remove all rolefunctions, appid records from ep_app_function
1118                         // that are associated with this app
1119                         sql = "DELETE FROM ep_app_function WHERE app_id='" + appid + "'";
1120                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1121                         query = localSession.createSQLQuery(sql);
1122                         query.executeUpdate();
1123
1124                         // Remove all records from fn_user_role associated with this app
1125                         sql = "delete from fn_user_role where app_id='" + appid + "'";
1126                         logQuery(sql);
1127                         query = localSession.createSQLQuery(sql);
1128                         query.executeUpdate();
1129
1130                         // Remove any widgets associated with this app
1131                         sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
1132                         logQuery(sql);
1133                         query = localSession.createSQLQuery(sql);
1134                         query.executeUpdate();
1135
1136                         // Remove any roles associated with this app
1137                         sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
1138                                         + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
1139                         logQuery(sql);
1140                         query = localSession.createSQLQuery(sql);
1141                         query.executeUpdate();
1142
1143                         // Remove all records from fn_role associated with this app
1144                         sql = "delete from fn_role where app_id='" + appid + "'";
1145                         logQuery(sql);
1146                         query = localSession.createSQLQuery(sql);
1147                         query.executeUpdate();
1148
1149                         // Remove app contact us entries
1150                         sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
1151                         logQuery(sql);
1152                         query = localSession.createSQLQuery(sql);
1153                         query.executeUpdate();
1154
1155                         // Remove rows in the app personalization selection table
1156                         sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
1157                         logQuery(sql);
1158                         query = localSession.createSQLQuery(sql);
1159                         query.executeUpdate();
1160
1161                         // Remove rows in the app personalization sort table
1162                         sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
1163                         logQuery(sql);
1164                         query = localSession.createSQLQuery(sql);
1165                         query.executeUpdate();
1166
1167                         // Remove rows in the app personalization sort table
1168                         sql = "delete from ep_user_roles_request where app_id='" + appid + "'";
1169                         logQuery(sql);
1170                         query = localSession.createSQLQuery(sql);
1171                         query.executeUpdate();
1172
1173                         // Remove rows in the app personalization sort table
1174                         sql = "delete from ep_web_analytics_source where app_id='" + appid + "'";
1175                         logQuery(sql);
1176                         query = localSession.createSQLQuery(sql);
1177                         query.executeUpdate();
1178
1179                         // Delete the app
1180                         sql = "delete from fn_app where app_id='" + appid + "'";
1181                         logQuery(sql);
1182                         query = localSession.createSQLQuery(sql);
1183                         query.executeUpdate();
1184
1185                         transaction.commit();
1186                         */
1187                         result = true;
1188                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteOnboardingApp success");
1189                 } catch (Exception e) {
1190                         logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
1191                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
1192                         EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
1193                 } finally {
1194                         EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
1195                 }
1196                 if (!result) {
1197                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1198                 }
1199                 return fieldsValidator;
1200         }
1201
1202         private static Object syncRests = new Object();
1203
1204         // An app has been enabled/disabled. Must enable/disable all associated
1205         // functional menu items.
1206         protected void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
1207                 String active_yn = enabled ? "Y" : "N";
1208                 String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
1209                                 + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
1210                                 + " AND r.app_id = '" + appId + "' ";
1211                 logQuery(sql);
1212                 @SuppressWarnings("unchecked")
1213                 List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
1214                 for (FunctionalMenuItem menuItem : menuItems) {
1215                         FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
1216                                         menuItem.menuId);
1217                         myMenuItem.active_yn = active_yn;
1218                         localSession.save(myMenuItem);
1219                 }
1220         }
1221
1222         // Attention! If (appId == null) we use this function to create application
1223         // otherwise we use it to modify existing application
1224         protected void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
1225                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
1226                 // Separate out the code for a restricted app, since it doesn't need any
1227                 // of the UEB code.
1228                 if (Boolean.TRUE.equals(onboardingApp.getRestrictedApp())) {
1229                         boolean result = false;
1230                         Session localSession = null;
1231                         Transaction transaction = null;
1232                         try {
1233                                 localSession = sessionFactory.openSession();
1234                                 transaction = localSession.beginTransaction();
1235                                 EPApp app;
1236                                 if (appId == null) {
1237                                         app = new EPApp();
1238                                 } else {
1239                                         app = (EPApp) localSession.get(EPApp.class, appId);
1240                                         if (app == null || app.getId() == null) { // App is already
1241                                                 // deleted!
1242                                                 transaction.commit();
1243                                                 localSession.close();
1244                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1245                                                 return;
1246                                         }
1247                                 }
1248                                 createAppFromOnboarding(app, onboardingApp, localSession);
1249                                 localSession.saveOrUpdate(app);
1250                                 // Enable or disable all menu items associated with this app
1251                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1252                                 transaction.commit();
1253                                 result = true;
1254                         } catch (Exception e) {
1255                                 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1256                                 EcompPortalUtils.rollbackTransaction(transaction,
1257                                                 "updateApp rollback, exception = " + e.toString());
1258                         } finally {
1259                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1260                         }
1261                         if (!result) {
1262                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1263                         }
1264
1265                 } else {
1266                         updateRestrictedApp(appId, onboardingApp, fieldsValidator, user);
1267                         
1268                 }
1269         }
1270         
1271
1272         protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1273                         EPUser user) {
1274                 synchronized (syncRests) {
1275                         boolean result = false;
1276                         Session localSession = null;
1277                         Transaction transaction = null;
1278                         try {
1279                                 localSession = sessionFactory.openSession();
1280                                 transaction = localSession.beginTransaction();
1281                                 EPApp app;
1282                                 if (appId == null) {
1283                                         app = new EPApp();
1284                                         /*
1285                                          * In the parent class, the UEB code is responsible for generating the
1286                                          * keys/secret/mailbox but UEB Messaging is not actually being used currently;
1287                                          * may be used in future at which point we can just remove this method and
1288                                          * depend on parent class's method So, using UUID generator to generate the
1289                                          * unique key instead.
1290                                          */
1291                                         String uuidStr = UUID.randomUUID().toString();
1292                                         String appKey = uuidStr;
1293                                         String appSecret = uuidStr;
1294                                         String appMailboxName = "ECOMP-PORTAL-OUTBOX";
1295                                         onboardingApp.setUebTopicName(appMailboxName);
1296                                         onboardingApp.setUebKey(appKey);
1297                                         onboardingApp.setUebSecret(appSecret);
1298                                 } else {
1299                                         app = (EPApp) localSession.get(EPApp.class, appId);
1300                                         if (app == null || app.getId() == null) {
1301                                                 // App is already deleted!
1302                                                 transaction.commit();
1303                                                 localSession.close();
1304                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1305                                                 return;
1306                                         }
1307                                 }
1308                                 logger.debug(EELFLoggerDelegate.debugLogger,
1309                                                 "updateRestrictedApp: about to call createAppFromOnboarding");
1310                                 createAppFromOnboarding(app, onboardingApp, localSession);
1311                                 logger.debug(EELFLoggerDelegate.debugLogger,
1312                                                 "updateRestrictedApp: finished calling createAppFromOnboarding");
1313                                 localSession.saveOrUpdate(app);
1314                                 logger.debug(EELFLoggerDelegate.debugLogger,
1315                                                 "updateRestrictedApp: finished calling localSession.saveOrUpdate");
1316                                 // Enable or disable all menu items associated with this app
1317                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1318                                 logger.debug(EELFLoggerDelegate.debugLogger,
1319                                                 "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled");
1320                                 transaction.commit();
1321                                 logger.debug(EELFLoggerDelegate.debugLogger,
1322                                                 "updateRestrictedApp: finished calling transaction.commit");
1323                                 result = true;
1324                         } catch (Exception e) {
1325                                 logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e);
1326                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1327                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1328                                 EcompPortalUtils.rollbackTransaction(transaction,
1329                                                 "updateRestrictedApp rollback, exception = " + e.toString());
1330                         } finally {
1331                                 EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp");
1332                         }
1333                         if (!result) {
1334                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1335                         }
1336                 }
1337
1338         }
1339
1340         @Deprecated
1341         protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator,
1342                         EPUser user) {
1343                 synchronized (syncRests) {
1344                         boolean result = false;
1345                         Session localSession = null;
1346                         Transaction transaction = null;
1347                         try {
1348                                 localSession = sessionFactory.openSession();
1349                                 transaction = localSession.beginTransaction();
1350                                 EPApp app;
1351                                 if (appId == null) {
1352                                         app = new EPApp();
1353                                         // -------------------------------------------------------------------------------------------
1354                                         // Register this App with the UEB communication server.
1355                                         // Save
1356                                         // the App's unique mailbox/topic
1357                                         // name and keys to the FN_APP table. The App's mailbox
1358                                         // and
1359                                         // keys will be visible to the
1360                                         // admin on the ONAP portal.
1361                                         // -------------------------------------------------------------------------------------------
1362                                         TopicManager topicManager = new TopicManager() {
1363
1364                                                 EPAppCommonServiceImpl service;
1365
1366                                                 public void init(EPAppCommonServiceImpl _service) {
1367                                                         service = _service;
1368                                                 }
1369
1370                                                 public void createTopic(String key, String secret, String topicName,
1371                                                                 String topicDescription) throws HttpException, CambriaApiException, IOException {
1372
1373                                                         init(EPAppCommonServiceImpl.this);
1374                                                         final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1375                                                         if (logger.isInfoEnabled()) {
1376                                                                 logger.info("==> createTopic");
1377                                                                 logger.info("topicName: " + topicName);
1378                                                                 logger.info("topicDescription: " + topicDescription);
1379                                                         }
1380                                                         CambriaTopicManager tm = null;
1381                                                         try {
1382                                                                 tm = service.getTopicManager(urlList, key, secret);
1383                                                         } catch (Exception e) {
1384                                                                 logger.error("pub.build Exception ", e);
1385                                                                 throw new CambriaApiException(topicName);
1386                                                         }
1387                                                         tm.createTopic(topicName, topicDescription, 1, 1);
1388                                                 }
1389
1390                                                 public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey,
1391                                                                 String topicName) throws HttpException, CambriaApiException, IOException {
1392                                                         logger.info("==> addPublisher to topic " + topicName);
1393                                                         final LinkedList<String> urlList = (LinkedList<String>) Helper.uebUrlList();
1394                                                         CambriaTopicManager tm = null;
1395                                                         try {
1396                                                                 tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret);
1397                                                         } catch (Exception e) {
1398                                                                 logger.error("pub.build Exception ", e);
1399                                                                 throw new CambriaApiException(topicName);
1400                                                         }
1401                                                         tm.allowProducer(topicName, publisherKey);
1402                                                 }
1403
1404                                         };
1405                                         final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
1406                                                         .usingHosts(Helper.uebUrlList()).build();
1407                                         com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
1408                                                         "ONAP Portal Owner");
1409                                         String appKey = credential.getApiKey();
1410                                         String appSecret = credential.getApiSecret();
1411                                         String appMailboxName = null;
1412
1413                                         int maxNumAttemptsToCreateATopic = 3;
1414                                         boolean successfullyCreatedMailbox = false;
1415                                         for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
1416                                                 appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
1417
1418                                                 try {
1419                                                         topicManager.createTopic(
1420                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1421                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1422                                                                         appMailboxName, "ECOMP outbox for app" + onboardingApp.getAppName());
1423                                                         successfullyCreatedMailbox = true;
1424                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1425                                                                         "Successfully created " + appMailboxName + " for App " + onboardingApp.getAppName());
1426                                                         logger.debug(EELFLoggerDelegate.debugLogger, "    Key = " + appKey + " Secret = "
1427                                                                         + appSecret + " generated using = " + user.getEmail());
1428                                                         break;
1429                                                 } catch (HttpException e) {
1430                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
1431                                                         if (e.getStatusCode() == 409) {
1432                                                                 logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
1433                                                                                 + " already exists. Will try using a different name", e);
1434                                                         } else {
1435                                                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
1436                                                                                 e);
1437                                                         }
1438                                                 }
1439                                         }
1440
1441                                         if (successfullyCreatedMailbox) {
1442                                                 onboardingApp.setUebTopicName(appMailboxName);
1443                                                 onboardingApp.setUebKey(appKey);
1444                                                 onboardingApp.setUebSecret(appSecret);
1445
1446                                                 try {
1447                                                         /*
1448                                                          * EP is a publisher to this App's new mailbox
1449                                                          */
1450                                                         topicManager.addPublisher(
1451                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1452                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
1453                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1454                                                                         appMailboxName);
1455
1456                                                         /*
1457                                                          * This App is a subscriber of its own mailbox
1458                                                          */
1459                                                         topicManager.addSubscriber(
1460                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1461                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1462                                                                         appMailboxName);
1463
1464                                                         /*
1465                                                          * This App is a publisher to EP
1466                                                          */
1467                                                         topicManager.addPublisher(
1468                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
1469                                                                         PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
1470                                                                         PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
1471                                                 } catch (HttpException | CambriaApiException | IOException e) {
1472                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1473                                                         logger.error(EELFLoggerDelegate.errorLogger,
1474                                                                         "Error when configuring Publisher/Subscriber for App's new mailbox", e);
1475                                                         transaction.commit();
1476                                                         localSession.close();
1477                                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1478                                                         return;
1479                                                 }
1480                                         } else {
1481                                                 transaction.commit();
1482                                                 localSession.close();
1483                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
1484                                                 return;
1485                                         }
1486                                 } else {
1487                                         app = (EPApp) localSession.get(EPApp.class, appId);
1488                                         if (app == null || app.getId() == null) {
1489                                                 // App is already deleted!
1490                                                 transaction.commit();
1491                                                 localSession.close();
1492                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
1493                                                 return;
1494                                         }
1495                                 }
1496                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
1497                                 createAppFromOnboarding(app, onboardingApp, localSession);
1498                                 logger.debug(EELFLoggerDelegate.debugLogger,
1499                                                 "LR: updateApp: finished calling createAppFromOnboarding");
1500                                 localSession.saveOrUpdate(app);
1501                                 logger.debug(EELFLoggerDelegate.debugLogger,
1502                                                 "LR: updateApp: finished calling localSession.saveOrUpdate");
1503                                 // Enable or disable all menu items associated with this app
1504                                 setFunctionalMenuItemsEnabled(localSession, onboardingApp.getIsEnabled(), appId);
1505                                 logger.debug(EELFLoggerDelegate.debugLogger,
1506                                                 "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
1507                                 transaction.commit();
1508                                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
1509                                 logger.debug(EELFLoggerDelegate.debugLogger,
1510                                                 "LR: updateApp: finished calling epUebHelper.addPublisher");
1511                                 result = true;
1512                         } catch (Exception e) {
1513                                 logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
1514                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
1515                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1516                                 EcompPortalUtils.rollbackTransaction(transaction,
1517                                                 "updateApp rollback, exception = " + e.toString());
1518                         } finally {
1519                                 EcompPortalUtils.closeLocalSession(localSession, "updateApp");
1520                         }
1521                         if (!result) {
1522                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1523                         }
1524                 }
1525
1526         }
1527
1528         public CambriaTopicManager getTopicManager(List<String> urlList, String key, String secret)
1529                         throws GeneralSecurityException, Exception {
1530                 throw new Exception("This method can only be invoked from child class");
1531         }
1532
1533         /**
1534          * Populates a transport model of the application from a database row model.
1535          * Leaves out the thumbnail because the FE fetches images via a different
1536          * API.
1537          * 
1538          * @param app
1539          *            Model of database row
1540          * @param onboardingApp
1541          *            Model for transport as JSON
1542          */
1543         @Override
1544         public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
1545                 onboardingApp.setId(app.getId());
1546                 onboardingApp.setAppName(app.getName());
1547                 onboardingApp.setImageUrl(app.getImageUrl());
1548                 onboardingApp.setAppDescription(app.getAppDescription());
1549                 onboardingApp.setAppNotes(app.getAppNotes());
1550                 onboardingApp.setLandingPage(app.getLandingPage());
1551                 onboardingApp.setAlternateLandingPage(app.getAlternateLandingPage());
1552                 onboardingApp.setRestUrl(app.getAppRestEndpoint());
1553                 onboardingApp.setIsOpen(app.getOpen());
1554                 onboardingApp.setIsEnabled(app.getEnabled());
1555                 onboardingApp.setAppBasicAuthUsername(app.getAppBasicAuthUsername());
1556                 
1557                 String effectivePwd = null;
1558                 if (app.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1559                         effectivePwd = EPCommonSystemProperties.APP_DISPLAY_PASSWORD;
1560                 else
1561                         effectivePwd = decryptedPassword(app.getAppBasicAuthPassword(), app);
1562                 
1563                 onboardingApp.setAppBasicAuthPassword(effectivePwd);
1564                 onboardingApp.setUebTopicName(app.getUebTopicName());
1565                 onboardingApp.setUebKey(app.getUebKey());
1566                 onboardingApp.setUebSecret(app.getUebSecret());
1567                 onboardingApp.setRolesInAAF(app.getRolesInAAF());
1568                 onboardingApp.setNameSpace(app.getNameSpace());
1569                 onboardingApp.setRestrictedApp(app.isRestrictedApp());
1570                 onboardingApp.setModeOfIntegration(app.getModeOfIntegration());
1571                 onboardingApp.setAppAck(app.getAppAck());
1572                 onboardingApp.setUsesCadi(app.getUsesCadi());
1573                 onboardingApp.setApplicationType(app.getAppType().toString());
1574         }
1575
1576         /**
1577          * Creates a database object for an application from an uploaded transport
1578          * model. Must decode the thumbnail, if any.
1579          * 
1580          * @param app
1581          * @param onboardingApp
1582          * @param localSession
1583          * @return The first argument.
1584          */
1585         protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
1586                 app.setName(onboardingApp.getAppName());
1587                 app.setAppDescription(onboardingApp.getAppDescription());
1588                 app.setAppNotes(onboardingApp.getAppNotes());
1589                 app.setLandingPage(onboardingApp.getLandingPage());
1590                 app.setAlternateLandingPage(onboardingApp.getAlternateLandingPage());
1591                 app.setAppRestEndpoint(onboardingApp.getRestUrl());
1592                 app.setOpen(onboardingApp.getIsOpen());
1593                 app.setEnabled(onboardingApp.getIsEnabled());
1594                 app.setAppBasicAuthUsername(onboardingApp.getAppBasicAuthUsername());
1595                 if(!onboardingApp.getAppBasicAuthPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD))
1596                 app.setAppBasicAuthPassword(this.encryptedPassword(onboardingApp.getAppBasicAuthPassword(), app));
1597                 //app.setUebTopicName(onboardingApp.uebTopicName);
1598                 app.setUebKey(onboardingApp.getUebKey());
1599                 app.setUebSecret(onboardingApp.getUebSecret());
1600                 app.setRolesInAAF(onboardingApp.getRolesInAAF());
1601                 app.setNameSpace(onboardingApp.getNameSpace());
1602                 app.setAppType(new Integer(onboardingApp.getApplicationType()));                
1603                 app.setModeOfIntegration(onboardingApp.getModeOfIntegration());
1604                 app.setAppAck(onboardingApp.getAppAck());
1605                 app.setUsesCadi(onboardingApp.getUsesCadi());
1606                 
1607                 
1608                 if (!StringUtils.isEmpty(onboardingApp.getThumbnail())) {
1609                         logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
1610                         String[] splitBase64Thumbnail = onboardingApp.getThumbnail().split("base64,");
1611                         logger.debug(EELFLoggerDelegate.debugLogger,
1612                                         "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
1613                         if (splitBase64Thumbnail.length > 1) {
1614                                 // This occurs when we have a new image, not an existing image
1615                                 byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
1616                                 logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
1617                                 // This is basically a boolean indicator that an image is
1618                                 // present.
1619                                 app.setImageUrl(constructImageName(onboardingApp));
1620                                 app.setThumbnail(decodedImage);
1621                         }
1622                 } else if (app.getThumbnail() != null && onboardingApp.getImageLink() == null) {
1623                         // The thumbnail that came in from the json is empty; the previous
1624                         // thumbnail is NOT empty. Must delete it.
1625                         logger.debug(EELFLoggerDelegate.debugLogger,
1626                                         "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
1627                         app.setImageUrl(null);
1628                         app.setThumbnail(null);
1629                 } else {
1630                         logger.debug(EELFLoggerDelegate.debugLogger,
1631                                         "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null");
1632                 }
1633                 return app;
1634         }
1635
1636         protected String constructImageName(OnboardingApp onboardingApp) {
1637                 String appLandingPageURL = onboardingApp.getLandingPage();
1638                 if(appLandingPageURL == null) {
1639                         appLandingPageURL = "";
1640                 }
1641                 return "portal_" + String.valueOf(appLandingPageURL.hashCode() + "_" + (int) (Math.random() * 100000.0))
1642                                 + ".png";
1643         }
1644
1645         // Don't encrypt or decrypt the password if it is null or the empty string
1646         private String decryptedPassword(String encryptedAppPwd, EPApp app) {
1647                 String result = "";
1648                 if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) {
1649                         try {
1650                                 result = CipherUtil.decryptPKC(encryptedAppPwd,
1651                                                 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1652                         } catch (Exception e) {
1653                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
1654                         }
1655                 }
1656                 return result;
1657         }
1658
1659         protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
1660                 String result = "";
1661                 if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) {
1662                         try {
1663                                 result = CipherUtil.encryptPKC(decryptedAppPwd,
1664                                                 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
1665                         } catch (Exception e) {
1666                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
1667                         }
1668                 }
1669                 return result;
1670         }
1671
1672         @SuppressWarnings("unchecked")
1673         @Override
1674         public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
1675                 FieldsValidator fieldsValidator = new FieldsValidator();
1676                 final Map<String, Long> params = new HashMap<>();
1677                 List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1678
1679                 try {
1680                         params.put("userId", user.getId());
1681                         epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1682                         Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1683                         for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
1684                                 existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
1685                         }
1686                         for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
1687                                 if (epWidgetsManPref.getWidgetid() != null) {
1688                                         Long widgetid = epWidgetsManPref.getWidgetid();
1689                                         if (existingWidgetsIds.containsKey(widgetid)) {
1690                                                 EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
1691                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1692                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1693                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1694                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1695                                                 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1696                                                 additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
1697                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
1698                                         } else {
1699                                                 EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
1700                                                 epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
1701                                                 epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
1702                                                 epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
1703                                                 epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
1704                                                 epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
1705                                                 epWidgetsManualSort.setUserId(user.getId());
1706                                                 dataAccessService.saveDomainObject(epWidgetsManualSort, null);
1707                                         }
1708                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1709                                 }
1710                         }
1711                 } catch (Exception e) {
1712                         logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
1713                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1714                 }
1715                 return fieldsValidator;
1716         }
1717
1718         @SuppressWarnings("unchecked")
1719         @Override
1720         public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
1721                 FieldsValidator fieldsValidator = new FieldsValidator();
1722                 final Map<String, Long> params = new HashMap<>();
1723                 List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
1724                 try {
1725                         params.put("userId", user.getId());
1726                         epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
1727                         Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
1728                         for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
1729                                 existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
1730                         }
1731                         for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
1732                                 if (delEpWidgetsManPref.getWidgetid() != null) {
1733                                         Long widgetId = delEpWidgetsManPref.getWidgetid();
1734                                         if (existingWidgetIds.containsKey(widgetId)) {
1735                                                 params.put("widgetId",widgetId);
1736                                                 dataAccessService.executeNamedQuery("deleteUserWidgetPlacement", params, null);
1737                                         }
1738                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1739                                 }
1740                         }
1741                 } catch (Exception e) {
1742                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
1743                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1744                 }
1745                 return fieldsValidator;
1746         }
1747
1748         /*
1749          * This Method Stores the Sort Order of User Apps by Sort Manual Preference
1750          *
1751          * @param: appsSortManual--contains User Apps Data
1752          *
1753          * @param: user--contains LoggedIn User Data
1754          */
1755         @SuppressWarnings("unchecked")
1756         @Override
1757         public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
1758                 FieldsValidator fieldsValidator = new FieldsValidator();
1759                 final Map<String, Long> params = new HashMap<>();
1760                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1761
1762                 try {
1763                         params.put("userId", user.getId());
1764                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1765                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1766                         for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
1767                                 existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
1768                         }
1769                         for (EPAppsManualPreference epAppsManPref : appsSortManual) {
1770                                 if (epAppsManPref.getAppid() != null) {
1771                                         Long appid = epAppsManPref.getAppid();
1772                                         if (existingAppIds.containsKey(appid)) {
1773                                                 EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
1774                                                 epAppsManualSort
1775                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1776                                                 HashMap<String, Long> additionalUpdateParam = new HashMap<>();
1777                                                 additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
1778                                                 dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
1779                                         } else {
1780                                                 EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
1781                                                 epAppsManualSort.setAppId(epAppsManPref.getAppid());
1782                                                 epAppsManualSort
1783                                                                 .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
1784                                                 epAppsManualSort.setUserId(user.getId());
1785                                                 dataAccessService.saveDomainObject(epAppsManualSort, null);
1786                                         }
1787                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1788                                 }
1789                         }
1790                 } catch (Exception e) {
1791                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
1792                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1793                 }
1794                 return fieldsValidator;
1795         }
1796
1797         /*
1798          * (non-Javadoc)
1799          *
1800          * @see org.onap.portalapp.portal.service.EPAppService#
1801          * deleteUserAppSortManual(java.lang.String,
1802          * org.onap.portalapp.portal.domain.EPUser)
1803          */
1804         @SuppressWarnings("unchecked")
1805         @Override
1806         public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
1807                 FieldsValidator fieldsValidator = new FieldsValidator();
1808                 final Map<String, Long> params = new HashMap<>();
1809                 List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
1810                 try {
1811                         params.put("userId", user.getId());
1812                         epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
1813                         Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
1814                         for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
1815                                 existingAppIds.put(userAppPref.getAppId(), userAppPref);
1816                         }
1817                         if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
1818                                 dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
1819                                                 "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
1820                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1821                         }
1822                 } catch (Exception e) {
1823                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
1824                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1825                 }
1826                 return fieldsValidator;
1827         }
1828
1829         @SuppressWarnings("unchecked")
1830         @Override
1831         public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
1832                 FieldsValidator fieldsValidator = new FieldsValidator();
1833                 final Map<String, Long> params = new HashMap<>();
1834                 List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
1835                 EPUserAppsSortPreference usrSortPr = null;
1836                 try {
1837                         params.put("userId", user.getId());
1838                         epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1839                         if (epSortTypes.size() == 0) {
1840                                 usrSortPr = new EPUserAppsSortPreference();
1841                                 usrSortPr.setUserId((int)(long)(user.getId()));
1842                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1843                                 dataAccessService.saveDomainObject(usrSortPr, null);
1844                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1845                         } else {
1846                                 usrSortPr = epSortTypes.get(0);
1847                                 usrSortPr.setSortPref(appsSortPreference.getValue());
1848                                 HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
1849                                 additionalUpdateParam.put("userId", usrSortPr.getUserId());
1850                                 dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
1851                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1852                         }
1853                 } catch (Exception e) {
1854                         logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
1855                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1856                 }
1857                 return fieldsValidator;
1858         }
1859
1860         @SuppressWarnings("unchecked")
1861         @Override
1862         public String getUserAppsSortTypePreference(EPUser user) {
1863                 final Map<String, Long> params = new HashMap<>();
1864                 List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
1865                 try {
1866                         params.put("userId", user.getId());
1867                         userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
1868                         if (userSortPrefs.size() > 0)
1869                                 return userSortPrefs.get(0).getSortPref();
1870                         else
1871                                 return null;
1872                 } catch (Exception e) {
1873                         logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
1874                 }
1875                 return null;
1876
1877         }
1878
1879         @Override
1880         public List<EPApp> getUserRemoteApps(String id) {
1881                 throw new RuntimeException(" Cannot be called from parent class");
1882         }
1883         
1884         @Override
1885         public UserRoles getUserProfileForLeftMenu(String loginId) {
1886                 final Map<String, String> params = new HashMap<>();
1887                 params.put("org_user_id", loginId);
1888                 @SuppressWarnings("unchecked")
1889                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null);
1890                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1891                 if (usersRolesList == null || usersRolesList.size() < 1)
1892                         return null;
1893
1894                 return usersRolesList.get(0);
1895         }
1896         
1897         
1898         @Override
1899         public UserRoles getUserProfileForRolesLeftMenu(String loginId) {
1900                 final Map<String, String> params = new HashMap<>();
1901                 params.put("org_user_id", loginId);
1902                 @SuppressWarnings("unchecked")
1903                 List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getRolesForLeftMenu", params, null);
1904                 ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
1905                 if (usersRolesList == null || usersRolesList.size() < 1)
1906                         return null;
1907
1908                 return usersRolesList.get(0);
1909         }
1910         
1911         @Override
1912         public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) {
1913                 // Check database.
1914                 UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId());
1915                 // If no roles are defined, treat this user as a guest.
1916                 if (user.isGuest() || userAndRoles == null) {
1917                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1918                                         user.getLoginId());
1919                         userAndRoles = createUserRoles(user);
1920                 }
1921
1922                 return userAndRoles;
1923         }
1924         
1925         @Override
1926         public UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user) {
1927                 // Check database.
1928                 UserRoles userAndRoles = getUserProfileForRolesLeftMenu(user.getLoginId());
1929                 // If no roles are defined, treat this user as a guest.
1930                 if (user.isGuest() || userAndRoles == null) {
1931                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest",
1932                                         user.getLoginId());
1933                         userAndRoles = createUserRoles(user);
1934                 }
1935
1936                 return userAndRoles;
1937         }
1938
1939         
1940         public UserRoles createUserRoles(EPUser user)
1941         {
1942                 UserRole userRole = new UserRole();
1943                 userRole.setUser_Id(user.getId());
1944                 userRole.setOrgUserId(user.getLoginId());
1945                 userRole.setFirstName(user.getFirstName());
1946                 userRole.setLastName(user.getLastName());
1947                 userRole.setRoleId(-1L);
1948                 userRole.setRoleName("Guest");
1949                 userRole.setUser_Id(-1L);
1950                 UserRoles userAndRoles = new UserRoles(userRole);
1951                 return userAndRoles;
1952                 
1953         }
1954
1955         @SuppressWarnings("unused")
1956         @Override
1957         public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception {
1958                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1959                 HttpEntity<String> entity = new HttpEntity<>(headers);
1960                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace);
1961                 ResponseEntity<String> response = null;
1962                 try {
1963                         
1964                         String namespaceUrl = SystemProperties.
1965                                         getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "nss/" + namespace;
1966                         
1967                         response = template.exchange(namespaceUrl, HttpMethod.GET, entity, String.class);
1968                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace ,
1969                                         response.getStatusCode().value());
1970                         if (response.getStatusCode().value() == 200) {
1971                                 String res = response.getBody();
1972                                 JSONObject jsonObj = new JSONObject(res);
1973                                 JSONArray namespaceArray = jsonObj.getJSONArray("ns");
1974                                 if(!namespaceArray.getJSONObject(0).has("admin")){
1975                                         logger.error(EELFLoggerDelegate.errorLogger,
1976                                                         "No admins are available for requested namespace:" + namespace);                
1977                                         throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1978                                                         "Portal Mechid is not an admin of" + namespace);
1979                                 }
1980                                 
1981                                 JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin");
1982                                 ArrayList<String> list = new ArrayList<String>();
1983                                 if (namespaceAdminArray != null) {
1984                                         int len = namespaceAdminArray.length();
1985                                         for (int i = 0; i < len; i++) {
1986                                                 list.add(namespaceAdminArray.get(i).toString());
1987                                         }
1988                                 }
1989                                 logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list);
1990                                 final String userName = SystemProperties
1991                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
1992                                 boolean idExists = list.stream().anyMatch(t -> userName.equals(t));
1993                                 if (false) {
1994                                         logger.error(EELFLoggerDelegate.errorLogger,
1995                                                         "Portal mechid is not admin of requested namespace:" + namespace);
1996                                         throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
1997                                                         "Portal Mechid is not an admin of" + namespace);
1998                                 }
1999                         }
2000                         
2001                 } catch (HttpClientErrorException e) {
2002                         logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
2003                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2004                                 throw e;
2005                 }
2006                 return response;
2007
2008         }
2009 }
2010