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