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