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