Null check for ClientResponse in PolicyUril.java
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / ExternalAccessRolesServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the “License”);
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.openecomp.portalapp.portal.service;
39
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.LinkedHashMap;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Set;
48 import java.util.SortedSet;
49 import java.util.TreeSet;
50 import java.util.stream.Collectors;
51
52 import org.apache.commons.lang.StringUtils;
53 import org.hibernate.Query;
54 import org.hibernate.Session;
55 import org.hibernate.SessionFactory;
56 import org.hibernate.Transaction;
57 import org.json.JSONArray;
58 import org.json.JSONObject;
59 import org.openecomp.portalapp.portal.domain.CentralRoleFunction;
60 import org.openecomp.portalapp.portal.domain.EPApp;
61 import org.openecomp.portalapp.portal.domain.EPAppRoleFunction;
62 import org.openecomp.portalapp.portal.domain.EPRole;
63 import org.openecomp.portalapp.portal.domain.EPUser;
64 import org.openecomp.portalapp.portal.domain.EPUserApp;
65 import org.openecomp.portalapp.portal.domain.ExternalRoleDetails;
66 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
67 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
68 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
69 import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction;
70 import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles;
71 import org.openecomp.portalapp.portal.transport.CentralApp;
72 import org.openecomp.portalapp.portal.transport.CentralRole;
73 import org.openecomp.portalapp.portal.transport.CentralUser;
74 import org.openecomp.portalapp.portal.transport.CentralUserApp;
75 import org.openecomp.portalapp.portal.transport.EcompUserRoles;
76 import org.openecomp.portalapp.portal.transport.ExternalAccessPerms;
77 import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail;
78 import org.openecomp.portalapp.portal.transport.ExternalAccessRole;
79 import org.openecomp.portalapp.portal.transport.ExternalAccessRolePerms;
80 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
81 import org.openecomp.portalapp.portal.transport.ExternalRoleDescription;
82 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
83 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
84 import org.openecomp.portalapp.portal.utils.PortalConstants;
85 import org.openecomp.portalsdk.core.domain.Role;
86 import org.openecomp.portalsdk.core.domain.RoleFunction;
87 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
88 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
89 import org.openecomp.portalsdk.core.restful.domain.EcompUser;
90 import org.openecomp.portalsdk.core.service.DataAccessService;
91 import org.openecomp.portalsdk.core.util.SystemProperties;
92 import org.springframework.beans.factory.annotation.Autowired;
93 import org.springframework.context.annotation.EnableAspectJAutoProxy;
94 import org.springframework.http.HttpEntity;
95 import org.springframework.http.HttpHeaders;
96 import org.springframework.http.HttpMethod;
97 import org.springframework.http.ResponseEntity;
98 import org.springframework.stereotype.Service;
99 import org.springframework.transaction.annotation.Transactional;
100 import org.springframework.web.client.HttpClientErrorException;
101 import org.springframework.web.client.RestTemplate;
102
103 import com.fasterxml.jackson.core.JsonProcessingException;
104 import com.fasterxml.jackson.databind.DeserializationFeature;
105 import com.fasterxml.jackson.databind.ObjectMapper;
106 import com.fasterxml.jackson.databind.type.TypeFactory;
107
108 @Service("externalAccessRolesService")
109 @EnableAspectJAutoProxy
110 @EPMetricsLog
111 @EPAuditLog
112 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
113
114         private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
115
116         private static final String OWNER = ".owner";
117
118         private static final String ADMIN = ".admin";
119
120         private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
121
122         private static final String FUNCTION_CD_LIKE_CLAUSE = " and function_cd like '%";
123
124         private static final String FUNCTION_PIPE = "|";
125
126         private static final String IS_NULL_STRING = "null";
127
128         private static final String EXTERNAL_AUTH_PERMS = "perms";
129
130         private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
131
132         private static final String WHERE_APP_ID_EQUALS = " where app_id = ";
133
134         private static final String IS_EMPTY_JSON_STRING = "{}";
135
136         private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
137
138         private static final String WHERE_ROLE_ID_EQUALS = " where role_id = ";
139
140         private static final String APP_ROLE_ID = "appRoleId";
141
142         private static final String APP_ID = "appId";
143
144         private static final String PRIORITY = "priority";
145
146         private static final String ACTIVE = "active";
147
148         private static final String ROLE_NAME = "name";
149
150         private static final String ID = "id";
151
152         private static final String WHERE_ROLE_NAME_EQUALS = " where role_name = '";
153
154         private static final String APP_ID_EQUALS = " app_id = ";
155
156         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
157
158         @Autowired
159         private DataAccessService dataAccessService;
160
161         @Autowired
162         private SessionFactory sessionFactory;
163
164         RestTemplate template = new RestTemplate();
165
166         @SuppressWarnings("unchecked")
167         public List<EPRole> getAppRoles(Long appId) throws Exception {
168                 List<EPRole> applicationRoles = null;
169                 String filter = null;
170                 try {
171                         if (appId == 1) {
172                                 filter = " where app_id is null";
173                         } else {
174                                 filter = WHERE_APP_ID_EQUALS + appId;
175                         }
176                         applicationRoles = dataAccessService.getList(EPRole.class, filter, null, null);
177                 } catch (Exception e) {
178                         logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
179                         throw new Exception(e.getMessage());
180                 }
181                 return applicationRoles;
182         }
183
184         @SuppressWarnings("unchecked")
185         @Override
186         public List<EPApp> getApp(String uebkey) throws Exception {
187                 List<EPApp> app = null;
188                 try {
189                         app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null);
190                         if(!app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
191                                 throw new Exception("Application:"+app.get(0).getName()+" is Unavailable");
192                         }
193                 } catch (Exception e) {
194                         logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
195                         throw new Exception(e.getMessage());
196                 }
197                 return app;
198         }
199
200         /**
201          * It returns  single application role from external auth system 
202          * @param addRole
203          * @param app
204          * @return JSON string which contains application role details
205          * @throws Exception
206          */
207         private String getSingleAppRole(String addRole, EPApp app) throws Exception {
208                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
209                 HttpEntity<String> entity = new HttpEntity<>(headers);
210                 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
211                 ResponseEntity<String> response = template
212                                 .exchange(
213                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
214                                                                 + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"),
215                                                 HttpMethod.GET, entity, String.class);
216                 logger.debug(EELFLoggerDelegate.debugLogger,
217                                 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ", response.getStatusCode().value());
218                 return response.getBody();
219         }
220
221         @Override
222         public boolean addRole(Role addRole, String uebkey) throws Exception {
223                 boolean response = false;
224                 ResponseEntity<String> addResponse = null;
225                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
226                 EPApp app = getApp(uebkey).get(0);
227                 String newRole = updateExistingRoleInExternalSystem(addRole, app);
228                 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
229                 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
230                 addResponse = template.exchange(
231                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
232                                 HttpMethod.POST, entity, String.class);
233                 if (addResponse.getStatusCode().value() == 201) {
234                         response = true;
235                         logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system  and response code: {} ", addResponse.getStatusCode().value());
236                 }
237                 if (addResponse.getStatusCode().value() == 406) {
238                         logger.error(EELFLoggerDelegate.errorLogger,
239                                         "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
240                 }
241                 return response;
242         }
243
244         /**
245          * 
246          * It deletes record in external auth system
247          * 
248          * @param delRole
249          * @return JSON String which has status code and response body 
250          * @throws Exception
251          */
252         private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
253                 ResponseEntity<String> delResponse = null;
254                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
255                 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
256                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
257                 delResponse = template.exchange(
258                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
259                                 HttpMethod.DELETE, entity, String.class);
260                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system and status code: {} ", delResponse.getStatusCode().value());
261                 return delResponse;
262         }
263
264         /**
265          * It updates role in external auth system
266          * 
267          * @param updateExtRole
268          * @param app
269          * @return true if success else false
270          * @throws Exception
271          *                                      If updateRoleInExternalSystem fails we catch it in logger for detail message
272          */
273         @SuppressWarnings("unchecked")
274         private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app) throws Exception {
275                 boolean response = false;
276                 ObjectMapper mapper = new ObjectMapper();
277                 ResponseEntity<String> deleteResponse = null;
278                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
279                 ExternalAccessRolePerms extRolePerms = null;
280                 ExternalAccessPerms extPerms = null;
281                 List<EPRole> epRoleList = null;
282                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
283                         epRoleList = dataAccessService.getList(EPRole.class,
284                                         WHERE_ROLE_ID_EQUALS + updateExtRole.getId() + " and app_id is null", null, null);
285                 } else {
286                         epRoleList = dataAccessService.getList(EPRole.class,
287                                         " where app_role_id = " + updateExtRole.getId() + " and app_id = " + app.getId(), null, null);
288                 }               
289                 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
290                 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
291                         JSONObject jsonObj = new JSONObject(appRole);
292                         JSONArray extRole = jsonObj.getJSONArray("role");
293                         if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
294                                 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
295                                 Map<String, String> delRoleKeyMapper = new HashMap<>();
296                                 delRoleKeyMapper.put(ROLE_NAME, roleName);
297                                 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
298                                 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
299                                 if (deleteResponse.getStatusCode().value() != 200) {
300                                         throw new Exception(deleteResponse.getBody());
301                                 }
302                                 addRole(updateExtRole, app.getUebKey());
303                         } else {
304                                 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
305                                 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
306                                 List<ExternalAccessPerms> list = null;
307                                 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
308                                         JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
309                                         list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
310                                                         .constructCollectionType(List.class, ExternalAccessPerms.class));
311                                 }
312                                 ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class);
313                                 // If role name or role functions are updated then delete record in External System and add new record to avoid conflicts
314                                 Boolean existingRoleActive;
315                                 boolean isActiveValueChanged;
316                                 // check role active status
317                                 existingRoleActive = new Boolean(sysRoleList.getActive());
318                                 isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive());
319                                 if (!sysRoleList.getName().equals(updateExtRole.getName())) {
320                                         Map<String, String> delRoleKeyMapper = new HashMap<>();
321                                         delRoleKeyMapper.put(ROLE_NAME, name);
322                                         String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);   
323                                         deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
324                                         if (deleteResponse.getStatusCode().value() != 200) {
325                                                 logger.error(EELFLoggerDelegate.errorLogger, "updateRoleInExternalSystem:  Failed to delete role in external system due to {} ", deleteResponse.getBody());
326                                                 throw new Exception(deleteResponse.getBody());
327                                         }
328                                         addRole(updateExtRole, app.getUebKey());
329                                         addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
330                                 }
331                                 boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),String.valueOf(updateExtRole.getPriority()));
332                                 ExternalAccessRole updateRole = new ExternalAccessRole();
333                                 if (!isActiveValueChanged
334                                                 || !checkPriorityStatus
335                                                 || sysRoleList.getId().equals(IS_NULL_STRING)
336                                                 || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
337                                         String updateDesc = "";
338                                         String appId = (app.getId().equals(PortalConstants.PORTAL_APP_ID)) ? " app_id is null"
339                                                         : APP_ID_EQUALS + app.getId();
340                                         List<EPRole> getRole = dataAccessService.getList(EPRole.class,
341                                                         WHERE_ROLE_NAME_EQUALS + updateExtRole.getName() + "' and " + appId, null, null);
342                                         Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
343                                         extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId()));
344                                         extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName()));
345                                         extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive()));
346                                         extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority()));
347                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
348                                                 extSystemUpdateRoleJsonMapper.put(APP_ID, "null");
349                                                 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null");
350                                         } else {
351                                                 extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId()));
352                                                 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, String.valueOf(getRole.get(0).getAppRoleId()));
353
354                                         }
355                                         updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
356                                         updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
357                                         updateRole.setDescription(updateDesc);
358                                         String updateRoleDesc = mapper.writeValueAsString(updateRole);
359                                         HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
360                                         logger.debug(EELFLoggerDelegate.debugLogger,
361                                                         "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
362                                         ResponseEntity<String> updatePermsResponse = template.exchange(
363                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
364                                                         HttpMethod.PUT, entity, String.class);
365                                         logger.debug(EELFLoggerDelegate.debugLogger,
366                                                         "updateRoleInExternalSystem: Finished updating in External Auth system and status code: {} ",
367                                                         updatePermsResponse.getStatusCode().value());
368                                 }
369                                 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
370                                 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
371                                 for (RoleFunction addPerm : roleFunctionListNew) {
372                                         updateRoleFunc.put(addPerm.getCode(), addPerm);
373                                 }
374                                 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
375                                 // Update permissions in the ExternalAccess System
376                                 if (list != null) {
377                                         for (ExternalAccessPerms perm : list) {
378                                                 if (!updateRoleFunc.containsKey(perm.getInstance())) {
379                                                         removePermForRole(perm, mapper, name, headers);
380                                                 }
381                                                 extRolePermMap.put(perm.getInstance(), perm);
382                                         }
383                                 }
384                                 response = true;
385                                 if (!roleFunctionListNew.isEmpty()) {
386                                         for (RoleFunction roleFunc : roleFunctionListNew) {
387                                                 if (!extRolePermMap.containsKey(roleFunc.getCode())) {
388                                                         String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
389                                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(),
390                                                                         "*");
391                                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
392                                                                         app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
393                                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
394                                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
395                                                         logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
396                                                         ResponseEntity<String> addResponse = template.exchange(
397                                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
398                                                                                         + "role/perm",
399                                                                         HttpMethod.POST, entity, String.class);
400                                                         if (addResponse.getStatusCode().value() != 201) {
401                                                                 response = false;
402                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
403                                                                                 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
404                                                                                 addResponse.getStatusCode().getReasonPhrase(),
405                                                                                 addResponse.getStatusCode().value());
406                                                         } else {
407                                                                 response = true;
408                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value());
409                                                         }
410                                                 }
411                                         }
412                                 }
413                         }
414                 } else {
415                         // It seems like role exists in local DB but not in External Access system
416                         addRole(updateExtRole, app.getUebKey());
417                         List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
418                         response = true;
419                         if (!roleFunctionListUpdate.isEmpty()) {
420                                 addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
421                         }
422                 }
423                 return response;
424         }
425         
426         /**
427          * 
428          * It adds functions to the role in external auth system 
429          * 
430          * @param updateExtRole
431          * @param addPermsMapper
432          * @param app
433          * @return true if success else false
434          * @throws Exception
435          */
436         private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app)
437                         throws Exception {
438                 boolean response = false;
439                 ExternalAccessRolePerms extAddRolePerms = null;
440                 ExternalAccessPerms extAddPerms = null;
441                 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
442                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
443                 for (RoleFunction roleFunc : roleFunctionListAdd) {
444                         String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
445                         extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), "*");
446                         extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
447                                         app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
448                         String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
449                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
450                         logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
451                         ResponseEntity<String> addResponse = template.exchange(
452                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
453                                         HttpMethod.POST, entity, String.class);
454                         if (addResponse.getStatusCode().value() != 201) {
455                                 response = false;
456                                 logger.debug(EELFLoggerDelegate.debugLogger,
457                                                 "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
458                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
459                         } else {
460                                 response = true;
461                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value());
462                         }
463                 }
464                 return response;
465         }
466
467         /**
468          * 
469          * It converts list of functions in updateExtRole parameter to the RoleFunction object
470          * 
471          * @param updateExtRole
472          * @return list of functions 
473          */
474         @SuppressWarnings("unchecked")
475         private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
476                 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
477                 List<RoleFunction> roleFunctionList = new ArrayList<>();
478                 ObjectMapper roleFuncMapper = new ObjectMapper();
479                 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
480                 while (itetaror.hasNext()) {
481                         Object nextValue = itetaror.next();
482                         RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
483                         roleFunctionList.add(roleFunction);
484                 }
485                 return roleFunctionList.stream().distinct().collect(Collectors.toList());
486         }
487
488         /**
489          * It delete permissions/functions in the external auth system
490          * 
491          * @param perm
492          * @param permMapper
493          * @param name
494          * @param headers
495          * @throws Exception
496          */
497         private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
498                         throws Exception {
499                 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
500                 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
501                 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
502                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
503                 ResponseEntity<String> deletePermResponse = template
504                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
505                                                 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
506                 if (deletePermResponse.getStatusCode().value() != 200) {
507                         throw new Exception(deletePermResponse.getBody());
508                 }
509                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system and status code: {}",
510                                 deletePermResponse.getStatusCode().value());
511         }
512
513         /**
514          * It will create new role in the External Auth System
515          * 
516          * @param newRole
517          * @param app
518          * @return true if successfully added in the system else false
519          * @throws Exception
520          *             If fails to add role in the system
521          */
522         private boolean addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception {
523                 boolean response = false;
524                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
525                 ObjectMapper mapper = new ObjectMapper();
526                 String addNewRole = "";
527                 ExternalAccessRole extRole = new ExternalAccessRole();
528                 String addDesc = null;
529                 Map<String, String> extSystemJsonMapper = new LinkedHashMap<>();
530                 extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId()));
531                 extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName()));
532                 extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive()));
533                 extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority()));
534                 extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId()));
535                 extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId()));
536                 addDesc = mapper.writeValueAsString(extSystemJsonMapper);
537                 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_"));
538                 extRole.setDescription(addDesc);
539                 addNewRole = mapper.writeValueAsString(extRole);
540                 HttpEntity<String> deleteEntity = new HttpEntity<>(addNewRole, headers);
541                 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
542                 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
543                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
544                                 HttpMethod.POST, deleteEntity, String.class);
545                 if (addNewRoleInExternalSystem.getStatusCode().value() != 201) {
546                         throw new Exception(addNewRoleInExternalSystem.getBody());
547                 } else {
548                         logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Finished adding into External Auth system and status code: {}",
549                                         addNewRoleInExternalSystem.getStatusCode().value());
550                         response = true;
551                 }
552                 return response;
553         }
554
555         /**
556          * 
557          * It updates existing role in the External Auth System
558          * 
559          * @param addRole
560          *            It Contains role information
561          * @param app
562          * @return string which is formatted to match with the external auth system
563          * @throws JsonProcessingException
564          */
565         @SuppressWarnings("unchecked")
566         private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
567                 ObjectMapper mapper = new ObjectMapper();
568                 String addNewRole = "";
569                 ExternalAccessRole extRole = new ExternalAccessRole();
570                 List<EPRole> role = null;
571                 String addDesc = null;
572                 Map<String, String> extSystemUpdateRole = new LinkedHashMap<>();
573                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
574                         role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId() + " and app_id is null", null, null);
575                 } else {
576                         role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId() + " and app_id ="+app.getId(), null, null);
577                 }
578                 extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId()));
579                 extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName()));
580                 extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive()));
581                 extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority()));
582                 extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId()));
583                 extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId()));
584                 addDesc = mapper.writeValueAsString(extSystemUpdateRole);
585                 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_"));
586                 extRole.setDescription(addDesc);
587                 addNewRole = mapper.writeValueAsString(extRole);
588                 return addNewRole;
589         }
590
591         /**
592          * It create a role in the external auth system and then in our local 
593          * 
594          * @param addRoleInDB
595          * @param app
596          * @return true else false
597          * @throws Exception
598          */
599         @SuppressWarnings("unchecked")
600         @Transactional
601         private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
602                 boolean result = false;
603                 List<EPRole> applicationRoles = null;
604                 EPRole epRole = null;
605                 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
606                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
607                 ObjectMapper mapper = new ObjectMapper();
608                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
609                 while (itetaror.hasNext()) {
610                         Object nextValue = itetaror.next();
611                         RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
612                         roleFunctionListNew.add(roleFunction);
613                 }
614                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
615                 try {
616                         if (addRoleInDB.getId() == null) { // check if it is new role
617                                 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
618                                 EPRole epRoleNew = new EPRole();
619                                 epRoleNew.setActive(addRoleInDB.getActive());
620                                 epRoleNew.setName(addRoleInDB.getName());
621                                 epRoleNew.setPriority(addRoleInDB.getPriority());
622                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
623                                         epRoleNew.setAppId(null);
624                                 } else {
625                                         epRoleNew.setAppId(app.getId());
626                                 }
627                                 dataAccessService.saveDomainObject(epRoleNew, null);
628                                 List<EPRole> getRoleCreated = null;
629                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
630                                         List<EPRole> roleCreated = dataAccessService.getList(EPRole.class,
631                                                         WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null,
632                                                         null);
633                                         EPRole epUpdateRole = roleCreated.get(0);
634                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
635                                         dataAccessService.saveDomainObject(epUpdateRole, null);
636                                         getRoleCreated = dataAccessService.getList(EPRole.class,
637                                                         WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null,
638                                                         null);
639                                 } else {
640                                         getRoleCreated = dataAccessService.getList(EPRole.class,
641                                                         WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id is null", null, null);
642                                 }
643                                 // Add role in External Auth system
644                                 result = addNewRoleInExternalSystem(getRoleCreated, app);
645                         } else { // if role already exists then update it
646                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
647                                         applicationRoles = dataAccessService.getList(EPRole.class,
648                                                         " where app_id is null " + " and role_id = " + addRoleInDB.getId(), null, null);
649                                 } else {
650                                         applicationRoles = dataAccessService.getList(EPRole.class,
651                                                         WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null);
652                                 }
653                                 if (applicationRoles.isEmpty()) {
654                                         applicationRoles = dataAccessService.getList(EPRole.class,
655                                                         WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + addRoleInDB.getName() + "'", null,
656                                                         null);
657                                 }
658                                 updateRoleInExternalSystem(addRoleInDB, app);
659                                 deleteRoleFunction(app, applicationRoles);
660                                 if (!applicationRoles.isEmpty()) {
661                                         epRole = applicationRoles.get(0);
662                                         epRole.setName(addRoleInDB.getName());
663                                         epRole.setPriority(addRoleInDB.getPriority());
664                                         epRole.setActive(addRoleInDB.getActive());
665                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
666                                                 epRole.setAppId(null);
667                                                 epRole.setAppRoleId(null);
668                                         } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
669                                                         && applicationRoles.get(0).getAppRoleId() == null) {
670                                                 epRole.setAppRoleId(epRole.getId());
671                                         }
672                                         dataAccessService.saveDomainObject(epRole, null);
673                                 }
674
675                                 saveRoleFunction(listWithoutDuplicates, app, applicationRoles);
676                                 result = true;
677                         }
678                 } catch (Exception e) {
679                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
680                         throw new Exception(e.getMessage());
681                 }
682                 return result;
683         }
684
685         /**
686          * 
687          * It validates whether role exists in external auth system
688          * 
689          * @param checkRole
690          * @param app
691          * @throws Exception
692          *                                      If role exits
693          */
694         private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
695                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
696                 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(" ", "_");
697                 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
698                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
699                 ResponseEntity<String> checkRoleInExternalSystem = template
700                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
701                                                 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
702                 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
703                         logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
704                         throw new Exception("Role already exists in external system");
705                 }
706         }
707
708         /**
709          * It saves list of functions to the role in portal
710          * 
711          * @param roleFunctionListNew
712          * @param app
713          * @param applicationRoles
714          * @throws Exception
715          */
716         @SuppressWarnings("unchecked")
717         private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles)
718                         throws Exception {
719                 for (RoleFunction roleFunc : roleFunctionListNew) {
720                         EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
721                         appRoleFunc.setAppId(app.getId());
722                         appRoleFunc.setRoleId(applicationRoles.get(0).getId());
723                         // query to check if function code is different for safe operation
724                         List<CentralRoleFunction> roleFunction = dataAccessService.getList(CentralRoleFunction.class,
725                                         WHERE_APP_ID_EQUALS+ app.getId()+FUNCTION_CD_LIKE_CLAUSE + roleFunc.getCode() + "'", null, null);
726                         appRoleFunc.setCode(roleFunction.get(0).getCode());
727                         dataAccessService.saveDomainObject(appRoleFunc, null);
728                 }
729         }
730         
731         /**
732          * It deletes all EPAppRoleFunction records in the portal
733          * 
734          * @param app
735          * @param role
736          */
737         @SuppressWarnings("unchecked")
738         private void deleteRoleFunction(EPApp app, List<EPRole> role) {
739                 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.getList(EPAppRoleFunction.class,
740                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + role.get(0).getId(), null, null);
741                 if (!appRoleFunctionList.isEmpty()) {
742                         for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
743                                 dataAccessService.deleteDomainObject(approleFunction, null);
744                         }
745                 }
746         }
747         
748         @Override
749         @SuppressWarnings("unchecked")
750         public List<EPUser> getUser(String loginId){
751                 return (List<EPUser>) dataAccessService.getList(EPUser.class,
752                                 " where org_user_id = '" + loginId + "'", null, null);
753         }
754
755         @Override
756         public String getUserWithRoles(String loginId, String uebkey) throws Exception {
757                 final Map<String, String> params = new HashMap<>();
758                 List<EPUser> userList = null;
759                 CentralUser cenUser = null;
760                 EPApp app = null;
761                 String result = null;
762                 try {
763                         params.put("orgUserIdValue", loginId);
764                         List<EPApp> appList = getApp(uebkey);
765                         if (!appList.isEmpty()) {
766                                 app = appList.get(0);
767                                 userList = getUser(loginId);
768                                 if (!userList.isEmpty()) {
769                                         EPUser user = userList.get(0);
770                                         ObjectMapper mapper = new ObjectMapper();
771                                         Set<EPUserApp> userAppSet = user.getEPUserApps();
772                                         cenUser = createEPUser(user, userAppSet, app);
773                                         result = mapper.writeValueAsString(cenUser);
774                                 } else if (userList.isEmpty()) {
775                                         throw new Exception("User not found");
776                                 }
777                         } else {
778                                 throw new Exception("Application not found");
779                         }
780                 } catch (Exception e) {
781                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
782                         throw new Exception(e.getMessage());
783                 }
784                 return result;
785         }
786
787         @Override
788         public List<CentralRole> getRolesForApp(String uebkey) throws Exception {
789                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
790                 List<CentralRole> roleList = new ArrayList<>();
791                 final Map<String, Long> params = new HashMap<>();
792                 try {
793                         List<EPApp> app = getApp(uebkey);
794                         List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
795                         createCentralRoleObject(app, appRolesList, roleList, params);
796                 } catch (Exception e) {
797                         throw new Exception("getRolesForApp Failed", e);
798                 }
799                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished getRolesForApp");
800                 return roleList;
801         }
802
803         @SuppressWarnings("unchecked")
804         @Override
805         public List<CentralRoleFunction> getRoleFuncList(String uebkey) throws Exception {
806                 EPApp app = getApp(uebkey).get(0);
807                 List<CentralRoleFunction> finalRoleList = new ArrayList<>();
808                 final Map<String, Long> params = new HashMap<>();
809                 params.put(APP_ID, app.getId());
810                 // Sync all functions from external system into Ecomp portal DB
811                 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Entering into syncRoleFunctionFromExternalAccessSystem");
812                 syncRoleFunctionFromExternalAccessSystem(app);
813                 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Finished syncRoleFunctionFromExternalAccessSystem");
814                 List<CentralRoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
815                 for(CentralRoleFunction roleFuncItem : getRoleFuncList ){
816                         if(roleFuncItem.getCode().contains(FUNCTION_PIPE)){
817                                 String code = "";
818                                 int count = StringUtils.countMatches(roleFuncItem.getCode(), FUNCTION_PIPE);
819                                 if (count == 2)
820                                         code = roleFuncItem.getCode().substring(
821                                                         roleFuncItem.getCode().indexOf(FUNCTION_PIPE) + 1,
822                                                         roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE));
823                                 else
824                                         code = roleFuncItem.getCode()
825                                                         .substring(roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
826                                 
827                                 roleFuncItem.setCode(code);
828                                 finalRoleList.add(roleFuncItem);
829                         } else{
830                                 finalRoleList.add(roleFuncItem);
831                         }
832                 }
833                 return finalRoleList;
834         }
835
836         /**
837          * It returns user detail information which is deep copy of EPUser.class object
838          * 
839          * @param userInfo
840          * @param userAppSet
841          * @param app
842          * @return
843          * @throws Exception
844          */
845         @SuppressWarnings("unchecked")
846         private CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
847
848                 final Map<String, Long> params = new HashMap<>();
849                 CentralUser userAppList = new CentralUser();
850                 CentralUser user1 = null;
851                 try {
852                         userAppList.userApps = new TreeSet<CentralUserApp>();
853                         for (EPUserApp userApp : userAppSet) {
854                                 if (userApp.getRole().getActive()) {
855                                         EPApp epApp = userApp.getApp();
856                                         String globalRole = userApp.getRole().getName().toLowerCase();
857                                         if (((epApp.getId().equals(app.getId()))
858                                                         && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
859                                                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
860                                                                         && (globalRole.toLowerCase().startsWith("global_")))) {
861                                                 CentralUserApp cua = new CentralUserApp();
862                                                 cua.setUserId(null);
863                                                 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
864                                                                 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
865                                                                 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
866                                                                 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
867                                                                 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
868                                                                 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
869                                                                 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
870                                                                 epApp.getUebTopicName());
871                                                 cua.setApp(cenApp);
872                                                 params.put("roleId", userApp.getRole().getId());
873                                                 params.put(APP_ID, userApp.getApp().getId());
874                                                 List<CentralRoleFunction> appRoleFunctionList = dataAccessService
875                                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
876                                                 SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
877                                                 for (CentralRoleFunction roleFunc : appRoleFunctionList) {
878                                                         String functionCode = "";
879                                                         if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
880                                                                 int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE);
881                                                                 String finalFunctionCodeVal;
882                                                                 if (count == 2)
883                                                                         finalFunctionCodeVal = roleFunc.getCode().substring(
884                                                                                         roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1,
885                                                                                         roleFunc.getCode().lastIndexOf(FUNCTION_PIPE));
886                                                                 else
887                                                                         finalFunctionCodeVal = roleFunc.getCode()
888                                                                                         .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
889
890                                                                 functionCode = finalFunctionCodeVal;
891                                                         } else {
892                                                                 functionCode = roleFunc.getCode();
893                                                         }
894                                                         CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), functionCode,
895                                                                         roleFunc.getName(), null, null);
896                                                         roleFunctionSet.add(cenRoleFunc);
897                                                 }
898                                                 Long userRoleId = null;
899                                                 if (globalRole.toLowerCase().startsWith("global_")
900                                                                 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
901                                                         userRoleId = userApp.getRole().getId();
902                                                 } else {
903                                                         userRoleId = userApp.getRole().getAppRoleId();
904                                                 }
905                                                 CentralRole cenRole = new CentralRole(userRoleId, userApp.getRole().getCreated(),
906                                                                 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
907                                                                 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
908                                                                 userApp.getRole().getName(), userApp.getRole().getActive(),
909                                                                 userApp.getRole().getPriority(), roleFunctionSet, null, null);
910                                                 cua.setRole(cenRole);
911
912                                                 userAppList.userApps.add(cua);
913                                         }
914                                 }
915                         }
916
917                         user1 = new CentralUser(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
918                                         userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
919                                         userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
920                                         userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
921                                         userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
922                                         userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
923                                         userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
924                                         userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
925                                         userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
926                                         userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
927                                         userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
928                                         userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
929                                         userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
930                                         userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
931                                         userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null);
932                 } catch (Exception e) {
933                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
934                         throw new Exception(e.getMessage());
935                 }
936
937                 return user1;
938         }
939
940         @SuppressWarnings("unchecked")
941         @Override
942         public CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception {
943                 final Map<String, Long> params = new HashMap<>();
944                 List<CentralRole> roleList = new ArrayList<>();
945                 CentralRole cenRole = new CentralRole();
946                 List<EPRole> roleInfo = null;
947                 List<EPApp> app = null;
948                 try {
949                         app = getApp(uebkey);
950                         if (app.isEmpty()) {
951                                 throw new Exception("Application not found");
952                         }
953                         String filter = null;
954                         if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
955                                 filter = WHERE_ROLE_ID_EQUALS + roleId + " and app_id is null ";
956                         } else {
957                                 filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId();
958
959                         }
960                         roleInfo = dataAccessService.getList(EPRole.class, filter, null, null);
961                         roleList = createCentralRoleObject(app, roleInfo, roleList, params);
962                         if (roleList.isEmpty()) {
963                                 return cenRole;
964                         }
965
966                 } catch (Exception e) {
967                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
968                         throw new Exception(e.getMessage());
969
970                 }
971                 return roleList.get(0);
972         }
973         
974         /**
975          * 
976          * It returns list of app roles along with role functions and which went through deep copy
977          * 
978          * @param app
979          * @param roleInfo
980          * @param roleList
981          * @param params
982          * @return
983          */
984         @SuppressWarnings("unchecked")
985         private List<CentralRole> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
986                         List<CentralRole> roleList, Map<String, Long> params) {
987                 for (EPRole role : roleInfo) {
988                         params.put("roleId", role.getId());
989                         params.put(APP_ID, app.get(0).getId());
990                         List<CentralRoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
991                                         params, null);
992                         SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
993                         for (CentralRoleFunction roleFunc : cenRoleFuncList) {
994                                 String functionCode = "";
995                                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
996                                         int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE);
997                                         String finalFunctionCodeVal;
998                                         if (count == 2)
999                                                 finalFunctionCodeVal = roleFunc.getCode().substring(
1000                                                                 roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1,
1001                                                                 roleFunc.getCode().lastIndexOf(FUNCTION_PIPE));
1002                                         else
1003                                                 finalFunctionCodeVal = roleFunc.getCode()
1004                                                                 .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
1005                                         functionCode = finalFunctionCodeVal;
1006                                 } else {
1007                                         functionCode = roleFunc.getCode();
1008                                 }
1009                                 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), functionCode,
1010                                                 roleFunc.getName(), null, null);
1011                                 roleFunctionSet.add(cenRoleFunc);
1012                         }
1013                         SortedSet<CentralRole> childRoles = new TreeSet<>();
1014                         CentralRole cenRole = null;
1015                         if (role.getAppRoleId() == null) {
1016                                 cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1017                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1018                                                 roleFunctionSet, childRoles, null);
1019                         } else {
1020                                 cenRole = new CentralRole(role.getAppRoleId(), role.getCreated(), role.getModified(),
1021                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1022                                                 role.getPriority(), roleFunctionSet, childRoles, null);
1023                         }
1024                         roleList.add(cenRole);
1025                 }
1026                 return roleList;
1027         }
1028
1029         @SuppressWarnings("unchecked")
1030         @Override
1031         public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1032                 CentralRoleFunction roleFunc = null;
1033                 EPApp app = getApp(uebkey).get(0);
1034                 List<CentralRoleFunction> getRoleFuncList = null;
1035                 final Map<String, String> params = new HashMap<>();
1036                 try {
1037                         params.put("functionCode", functionCode);
1038                         params.put(APP_ID, String.valueOf(app.getId()));
1039                         getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null);
1040                         if (getRoleFuncList.isEmpty()) {
1041                                 return roleFunc;
1042                         } else{
1043                                 String functionCodeFormat = getRoleFuncList.get(0).getCode();
1044                                 if(functionCodeFormat.contains(FUNCTION_PIPE)){
1045                                         String newfunctionCodeFormat = functionCodeFormat.substring(functionCodeFormat.lastIndexOf(FUNCTION_PIPE)+1); 
1046                                         roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), newfunctionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl());
1047                                 } else{
1048                                         roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), functionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl());
1049                                 }
1050                         }
1051                 } catch (Exception e) {
1052                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1053                         throw new Exception("getRoleFunction failed", e);
1054                 }
1055                 return roleFunc;
1056         }
1057
1058         @Override
1059         public boolean saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1060                 boolean saveOrUpdateFunction = false;
1061                 try {
1062                         addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1063                         dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1064                         saveOrUpdateFunction = true;
1065                 } catch (Exception e) {
1066                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1067                         saveOrUpdateFunction = false;
1068                 }
1069                 return saveOrUpdateFunction;
1070         }
1071         
1072         /**
1073          * It creates application permission in external auth system
1074          * 
1075          * @param domainCentralRoleFunction
1076          * @param app
1077          * @throws Exception
1078          */
1079         @SuppressWarnings("unchecked")
1080         private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
1081                         throws Exception {
1082                 ObjectMapper mapper = new ObjectMapper();
1083                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1084                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1085                 List<CentralRoleFunction> appRoleFunc = dataAccessService.getList(CentralRoleFunction.class,
1086                                 WHERE_APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + domainCentralRoleFunction.getCode() + "'", null, null);
1087                 String roleFuncName = null;
1088                 if (!appRoleFunc.isEmpty()) {
1089                         roleFuncName = appRoleFunc.get(0).getCode();
1090                 } else {
1091                         roleFuncName = domainCentralRoleFunction.getCode();
1092                 }
1093                 String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1094                 HttpEntity<String> getSinglePermEntity = new HttpEntity<>(headers);
1095                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} ", CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1096                 ResponseEntity<String> getResponse = template.exchange(
1097                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/"
1098                                                 + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*",
1099                                 HttpMethod.GET, getSinglePermEntity, String.class);
1100                 if (getResponse.getStatusCode().value() != 200) {
1101                         EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
1102                         throw new Exception(getResponse.getBody());
1103                 }
1104                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished GET permission from External Auth system and response: {} ", getResponse.getBody());
1105                 String res = getResponse.getBody();
1106                 if (res.equals(IS_EMPTY_JSON_STRING)) {
1107                         try {
1108                                 extPerms.setAction("*");
1109                                 extPerms.setInstance(domainCentralRoleFunction.getCode());
1110                                 extPerms.setType(app.getNameSpace() + "." + checkType);
1111                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1112                                 String updateRole = mapper.writeValueAsString(extPerms);
1113                                 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1114                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1115                                 ResponseEntity<String> addPermResponse= template.exchange(
1116                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1117                                                 HttpMethod.POST, entity, String.class);
1118                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission in  and status code: {} ", addPermResponse.getStatusCode().value());
1119                         } catch(HttpClientErrorException e){
1120                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1121                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1122                         }catch (Exception e) {
1123                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1124                                                 e);
1125                         }
1126                 } else {
1127                         try {
1128                                 extPerms.setAction("*");
1129                                 extPerms.setInstance(domainCentralRoleFunction.getCode());
1130                                 extPerms.setType(app.getNameSpace() + "." + checkType);
1131                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1132                                 String updateRole = mapper.writeValueAsString(extPerms);
1133                                 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1134                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1135                                 ResponseEntity<String> updatePermResponse = template.exchange(
1136                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1137                                                 HttpMethod.PUT, entity, String.class);
1138                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system and response: {} ", updatePermResponse.getBody());
1139                         } catch(HttpClientErrorException e){
1140                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1141                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1142                         } catch (Exception e) {
1143                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
1144                                                 e);
1145                         }
1146                 }
1147         }
1148
1149         @Override
1150         @Transactional
1151         public boolean deleteCentralRoleFunction(String code, EPApp app) {
1152                 boolean deleteFunctionResponse = false;
1153                 try {
1154                         final Map<String, String> params = new HashMap<>();
1155                         params.put("functionCode", code);
1156                         params.put(APP_ID, String.valueOf(app.getId()));
1157                         CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService
1158                                         .executeNamedQuery("getRoleFunction", params, null).get(0);
1159                         deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1160                         // Delete role function dependency records
1161                         deleteAppRoleFunctions(code, app);
1162                         dataAccessService.deleteDomainObject(domainCentralRoleFunction, null);
1163                         deleteFunctionResponse = true;
1164                 } catch (Exception e) {
1165                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1166                 }
1167                 return deleteFunctionResponse;
1168         }
1169
1170         /**
1171          * It deletes app function record in portal 
1172          * 
1173          * @param code
1174          * @param app
1175          */
1176         private void deleteAppRoleFunctions(String code, EPApp app) {
1177                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1178                                 APP_ID_EQUALS + app.getId() + FUNCTION_CD_LIKE_CLAUSE + code + "'", null);
1179         }
1180         
1181         /**
1182          * 
1183          * It deletes permission in the external auth system  
1184          * 
1185          * @param domainCentralRoleFunction
1186          * @param app
1187          * @throws Exception
1188          */
1189         private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
1190                         throws Exception {
1191                 try {
1192                         ObjectMapper mapper = new ObjectMapper();
1193                         ExternalAccessPerms extPerms = new ExternalAccessPerms();
1194                         String instanceValue = "";
1195                         if(domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1196                                 instanceValue = domainCentralRoleFunction.getCode().substring(domainCentralRoleFunction.getCode().lastIndexOf(FUNCTION_PIPE)+1);
1197                         }else{
1198                                 instanceValue = domainCentralRoleFunction.getCode();
1199                         }
1200                         String checkType = instanceValue.contains("menu") ? "menu" : "url";
1201                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1202                         extPerms.setAction("*");
1203                         extPerms.setInstance(domainCentralRoleFunction.getCode());
1204                         extPerms.setType(app.getNameSpace() + "." + checkType);
1205                         extPerms.setDescription(domainCentralRoleFunction.getName());
1206                         String updateRole = mapper.writeValueAsString(extPerms);
1207                         HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1208                         logger.debug(EELFLoggerDelegate.debugLogger,"deleteRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1209                         ResponseEntity<String> delPermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1210                                         + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1211                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system and status code: {} ", delPermResponse.getStatusCode().value());
1212                 } catch(HttpClientErrorException e){
1213                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1214                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1215                 } catch (Exception e) {
1216                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1217                                 logger.debug(EELFLoggerDelegate.debugLogger,
1218                                                 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
1219                                                 e.getMessage());
1220                         } else {
1221                                 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1222                         }
1223                 }
1224         }
1225
1226         @Override
1227         public boolean saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1228                 boolean addRoleResponse = false;
1229                 try {
1230                         EPApp app = getApp(uebkey).get(0);
1231                         addRoleInEcompDB(saveRole, app);
1232                         addRoleResponse = true;
1233                 } catch (Exception e) {
1234                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1235                 }
1236                 return addRoleResponse;
1237         }
1238
1239         @SuppressWarnings("unchecked")
1240         @Override
1241         public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1242                 Session localSession = sessionFactory.openSession();
1243                 Transaction transaction = null;
1244                 boolean result = false;
1245                 try {
1246                         transaction = localSession.beginTransaction();
1247
1248                         List<EPRole> epRoleList = null;
1249                         ResponseEntity<String> deleteResponse = null;
1250                         EPApp app = getApp(uebkey).get(0);
1251                         if (app.getId() == 1) {
1252                                 epRoleList = dataAccessService.getList(EPRole.class,
1253                                                 " where app_id is null " + "and role_name = '" + deleteRole + "'", null, null);
1254                         } else {
1255                                 epRoleList = dataAccessService.getList(EPRole.class,
1256                                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + deleteRole + "'", null, null);
1257                         }
1258                         // Delete app role functions before deleting role
1259                         deleteRoleFunction(app, epRoleList);
1260                         if (app.getId() == 1) {
1261                                 // Delete fn_user_ role
1262                                 dataAccessService.deleteDomainObjects(EPUserApp.class,
1263                                                 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1264
1265                                 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId());
1266                         }
1267                         // Delete Role in External System
1268                         String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "."
1269                                         + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}";
1270                         deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1271                         if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1272                                 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1273                                 logger.error(EELFLoggerDelegate.errorLogger,
1274                                                 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1275                                                 deleteResponse.getBody());
1276                         }
1277                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1278                         transaction.commit();
1279                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1280                         dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1281                         result = true;
1282                 } catch (Exception e) {
1283                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1284                         result = false;
1285                 } finally {
1286                         localSession.close();
1287                 }
1288                 return result;
1289         }
1290
1291         /**
1292          * 
1293          * It deletes application user role in external auth system
1294          * 
1295          * @param role
1296          * @param app
1297          * @param LoginId
1298          * @throws Exception
1299          */
1300         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1301                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1302                 HttpEntity<String> entity = new HttpEntity<>(headers);
1303                 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1304                 ResponseEntity<String> getResponse = template
1305                                 .exchange(
1306                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1307                                                                 + LoginId
1308                                                                 + SystemProperties
1309                                                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1310                                                                 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
1311                                                 HttpMethod.GET, entity, String.class);
1312                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1313                 if (getResponse.getStatusCode().value() != 200) {
1314                         throw new Exception(getResponse.getBody());
1315                 }
1316                 String res = getResponse.getBody();
1317                 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1318                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1319                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1320                         ResponseEntity<String> deleteResponse = template
1321                                         .exchange(
1322                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1323                                                                         + "userRole/" + LoginId
1324                                                                         + SystemProperties
1325                                                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1326                                                                         + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
1327                                                         HttpMethod.DELETE, userRoleentity, String.class);
1328                         if (deleteResponse.getStatusCode().value() != 200) {
1329                                 throw new Exception("Failed to delete user role");
1330                         }
1331                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1332                 }
1333         }
1334
1335         @SuppressWarnings("unchecked")
1336         @Override
1337         public List<CentralRole> getActiveRoles(String uebkey) throws Exception {
1338                 List<CentralRole> roleList = new ArrayList<>();
1339                 try {
1340                         List<EPApp> app = getApp(uebkey);
1341                         final Map<String, Long> params = new HashMap<>();
1342                         // check if portal
1343                         Long appId = null;
1344                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1345                                 appId = app.get(0).getId();
1346                         }
1347                         List<EPRole> epRole = dataAccessService.getList(EPRole.class,
1348                                         WHERE_APP_ID_EQUALS + appId + " and active_yn = 'Y'", null, null);
1349                         roleList = createCentralRoleObject(app, epRole, roleList, params);
1350                 } catch (Exception e) {
1351                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1352                         throw new Exception(e.getMessage());
1353                 }
1354                 return roleList;
1355
1356         }
1357
1358         @SuppressWarnings("unchecked")
1359         @Override
1360         public boolean deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1361                 boolean result = false;
1362                 Session localSession = sessionFactory.openSession();
1363                 Transaction transaction = null;
1364                 EPApp app = null;
1365                 try {
1366                         transaction = localSession.beginTransaction();
1367                         List<EPRole> epRoleList = null;
1368                         app = getApp(uebkey).get(0);
1369                         epRoleList = dataAccessService.getList(EPRole.class,
1370                                         WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + roleId, null, null);
1371                         if (epRoleList.isEmpty()) {
1372                                 epRoleList = dataAccessService.getList(EPRole.class,
1373                                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + roleId, null, null);
1374                         }
1375                         // Delete User Role in External System before deleting role
1376                         deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1377                         // Delete user app roles
1378                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1379                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1380
1381                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId());
1382                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: about to commit the transaction");
1383                         transaction.commit();
1384                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1385                         result = true;
1386                 } catch(HttpClientErrorException e){
1387                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1388                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1389                 } catch (Exception e) {
1390                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1391                         EcompPortalUtils.rollbackTransaction(transaction,
1392                                         "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1393                 } finally {
1394                         localSession.close();
1395                 }
1396                 return result;
1397         }
1398
1399         @Override
1400         @SuppressWarnings("unchecked")
1401         @Transactional
1402         public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1403                 try {
1404                         ResponseEntity<String> response = null;
1405                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1406                         HttpEntity<String> entity = new HttpEntity<>(headers);
1407                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1408                         response = template
1409                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1410                                                         + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1411
1412                         String res = response.getBody();
1413                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ", response.getBody());
1414                         JSONObject jsonObj = new JSONObject(res);
1415                         JSONArray extPerms = jsonObj.getJSONArray("perm");
1416                         for (int i = 0; i < extPerms.length(); i++) {
1417                                 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
1418                                         extPerms.remove(i);
1419                                         i--;
1420                                 }
1421                         }
1422                         ExternalAccessPermsDetail permDetails = null;
1423                         List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
1424                         for (int i = 0; i < extPerms.length(); i++) {
1425                                 String description = null;
1426                                 if(extPerms.getJSONObject(i).has("description")){
1427                                         description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1428                                 } else{
1429                                         description = extPerms.getJSONObject(i).getString("instance");
1430                                 }
1431                                 if (extPerms.getJSONObject(i).has("roles")) {
1432                                         ObjectMapper rolesListMapper = new ObjectMapper();
1433                                         JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
1434                                         List<String> list = rolesListMapper.readValue(resRoles.toString(),
1435                                                         TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
1436                                         permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1437                                                         extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
1438                                                                         + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1439                                                                         + extPerms.getJSONObject(i).getString("action"),
1440                                                         extPerms.getJSONObject(i).getString("action"), list, description);
1441                                         permsDetailList.add(permDetails);
1442                                 } else {
1443                                         permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1444                                                         extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
1445                                                                         + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1446                                                                         + extPerms.getJSONObject(i).getString("action"),
1447                                                         extPerms.getJSONObject(i).getString("action"), description);
1448                                         permsDetailList.add(permDetails);
1449                                 }
1450                         }
1451
1452                         final Map<String, Long> params = new HashMap<>();
1453                         final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>();
1454                         params.put(APP_ID, app.getId());
1455                         List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1456                                         null);
1457                         if (!appFunctions.isEmpty()) {
1458                                 for (CentralRoleFunction roleFunc : appFunctions) {
1459                                         roleFuncMap.put(roleFunc.getCode(), roleFunc);
1460                                 }
1461                         }
1462                         // delete all application role functions
1463                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
1464                         // Add if new functions and app role functions were added in external auth system
1465                         for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1466                                 String code = permsDetail.getInstance();
1467                                 CentralRoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1468                                 if (null == getFunctionCodeKey) {
1469                                         String finalFunctionCodeVal = "";
1470                                         if (permsDetail.getInstance().contains(FUNCTION_PIPE)) {
1471                                                 int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE);
1472                                                 if (count == 2)
1473                                                         finalFunctionCodeVal = permsDetail.getInstance().substring(
1474                                                                         permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1,
1475                                                                         permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE));
1476                                                 else
1477                                                         finalFunctionCodeVal = permsDetail.getInstance()
1478                                                                         .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1);
1479                                         } else {
1480                                                 finalFunctionCodeVal = permsDetail.getInstance();
1481                                         }
1482                                         CentralRoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
1483                                         if (null == checkIfCodeStillExits) {
1484                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1485                                                                 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
1486                                                 addFunctionInEcompDB(app, permsDetail, code);
1487                                                 logger.debug(EELFLoggerDelegate.debugLogger,
1488                                                                 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
1489
1490                                         }
1491                                 }                               
1492                                 List<EPRole> epRolesList = null;
1493                                 List<String> roles = permsDetail.getRoles();
1494                                 if (roles != null) {
1495                                         for (String roleList : roles) {
1496                                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1497                                                         epRolesList = dataAccessService.getList(EPRole.class,
1498                                                                         " where app_id is null " + " and role_name = '"
1499                                                                                         + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ")
1500                                                                                         + "'",
1501                                                                         null, null);
1502                                                 } else {
1503                                                         epRolesList = dataAccessService.getList(EPRole.class,
1504                                                                         WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1505                                                                                         + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ")
1506                                                                                         + "'",
1507                                                                         null, null);
1508                                                 }
1509                                                 if (epRolesList.isEmpty()) {
1510                                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1511                                                                 epRolesList = dataAccessService.getList(EPRole.class,
1512                                                                                 " where app_id is null " + " and role_name = '"
1513                                                                                                 + roleList.substring(app.getNameSpace().length() + 1) + "'",
1514                                                                                 null, null);
1515                                                         } else {
1516                                                                 epRolesList = dataAccessService.getList(EPRole.class,
1517                                                                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1518                                                                                                 + roleList.substring(app.getNameSpace().length() + 1) + "'",
1519                                                                                 null, null);
1520                                                         }
1521                                                         // Adding new role thats does not exits in Local but exists in external access system
1522                                                         if (epRolesList.isEmpty()) {
1523                                                                 Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
1524                                                                 addIfRoleDescriptionNotExitsInExtSystem(role, app);
1525                                                                 epRolesList = dataAccessService.getList(EPRole.class,
1526                                                                                 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1527                                                                                                 + role.getName() + "'",
1528                                                                                 null, null);
1529                                                         }
1530                                                 }
1531                                                 // save all application role functions
1532                                                 if (!epRolesList.isEmpty()) {
1533                                                         try {
1534                                                                 List<CentralRoleFunction> roleFunctionList = null;
1535                                                                 String functionCode = "";
1536                                                                 if (permsDetail.getInstance().contains(FUNCTION_PIPE)) {
1537                                                                         int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE);
1538                                                                         String finalFunctionCodeVal;
1539                                                                         if (count == 2)
1540                                                                                 finalFunctionCodeVal = permsDetail.getInstance().substring(
1541                                                                                                 permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1,
1542                                                                                                 permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE));
1543                                                                         else
1544                                                                                 finalFunctionCodeVal = permsDetail.getInstance()
1545                                                                                                 .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1);
1546
1547                                                                         functionCode = finalFunctionCodeVal;
1548                                                                 }
1549                                                                 roleFunctionList = dataAccessService.getList(CentralRoleFunction.class,
1550                                                                                 " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + functionCode + "'",
1551                                                                                 null, null);
1552                                                                 if (roleFunctionList.isEmpty()) {
1553                                                                         roleFunctionList = dataAccessService.getList(CentralRoleFunction.class,
1554                                                                                         " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'",
1555                                                                                         null, null);
1556                                                                 }
1557                                                                 if (!roleFunctionList.isEmpty()) {
1558                                                                         EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1559                                                                         addAppRoleFunc.setAppId(app.getId());
1560                                                                         addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1561                                                                         addAppRoleFunc.setRoleId(epRolesList.get(0).getId());
1562                                                                         dataAccessService.saveDomainObject(addAppRoleFunc, null);
1563                                                                 }
1564                                                         } catch (Exception e) {
1565                                                                 logger.error(EELFLoggerDelegate.errorLogger,
1566                                                                                 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
1567                                                                                 e);
1568                                                         }
1569                                                 }
1570                                         }
1571                                 }
1572                         }
1573                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1574                 } catch (Exception e) {
1575                         logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1576
1577                 }
1578         }
1579         
1580         /**
1581          * 
1582          * Add function into local DB
1583          * 
1584          * @param app
1585          * @param permsDetail
1586          * @param code
1587          */
1588         private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
1589                 try{
1590                 CentralRoleFunction addFunction = new CentralRoleFunction();
1591                 addFunction.setAppId(app.getId());
1592                 addFunction.setCode(code);
1593                 addFunction.setName(permsDetail.getDescription());
1594                 dataAccessService.saveDomainObject(addFunction, null);
1595                 } catch(Exception e){
1596                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
1597                 }
1598         }
1599
1600         /**
1601          * 
1602          * It updates description of a role in external auth system
1603          * 
1604          * @param role
1605          * @param app
1606          * @throws Exception
1607          */
1608         private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
1609                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
1610                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1611                 try {
1612                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1613                         template.exchange(
1614                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1615                                         HttpMethod.PUT, entity, String.class);
1616                 } catch (HttpClientErrorException e) {
1617                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
1618                                         e);
1619                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1620                 } catch (Exception e) {
1621                         logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
1622                                         e);
1623                 }
1624         }
1625
1626         /**
1627          * 
1628          * While sync functions form external auth system if new role found we should add in local and return Role.class object
1629          * 
1630          * @param app
1631          * @param role
1632          * @return
1633          */
1634         @SuppressWarnings("unchecked")
1635         private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
1636                 Role setNewRole = new Role();
1637                 EPRole epRoleNew = new EPRole();
1638                 try {
1639                         epRoleNew.setActive(true);
1640                         epRoleNew.setName(role);
1641                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1642                                 epRoleNew.setAppId(null);
1643                         } else {
1644                                 epRoleNew.setAppId(app.getId());
1645                         }
1646                         dataAccessService.saveDomainObject(epRoleNew, null);
1647                         List<EPRole> getRoleCreated = null;
1648                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1649                                 List<EPRole> roleCreated = dataAccessService.getList(EPRole.class,
1650                                                 WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null);
1651                                 EPRole epUpdateRole = roleCreated.get(0);
1652                                 epUpdateRole.setAppRoleId(epUpdateRole.getId());
1653                                 dataAccessService.saveDomainObject(epUpdateRole, null);
1654                                 getRoleCreated = dataAccessService.getList(EPRole.class,
1655                                                 WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null);
1656                         } else {
1657                                 getRoleCreated = dataAccessService.getList(EPRole.class,
1658                                                 WHERE_ROLE_NAME_EQUALS + role + "' and app_id is null", null, null);
1659                         }
1660                         EPRole roleObject = getRoleCreated.get(0);
1661                         setNewRole.setId(roleObject.getId());
1662                         setNewRole.setName(roleObject.getName());
1663                         setNewRole.setActive(roleObject.getActive());
1664                         setNewRole.setPriority(roleObject.getPriority());
1665                 } catch (Exception e) {
1666                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
1667                 }
1668                 return setNewRole;
1669         }
1670
1671         @Override
1672         @SuppressWarnings("unchecked")
1673         public Integer bulkUploadFunctions(String uebkey) throws Exception {
1674                 EPApp app = getApp(uebkey).get(0);
1675                 List<RoleFunction> roleFuncList = null;
1676                 roleFuncList = dataAccessService.getList(RoleFunction.class, null);
1677                 CentralRoleFunction cenRoleFunc = null;
1678                 Integer functionsAdded = 0;
1679                 try {
1680                         for (RoleFunction roleFunc : roleFuncList) {
1681                                 cenRoleFunc = new CentralRoleFunction(roleFunc.getCode(), roleFunc.getName());
1682                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1683                                 functionsAdded++;
1684                         }
1685                 } catch(HttpClientErrorException e){
1686                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
1687                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1688                 } catch (Exception e) {
1689                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
1690                 }
1691                 return functionsAdded;
1692         }
1693
1694         @Override
1695         public Integer bulkUploadRoles(String uebkey) throws Exception {
1696                 List<EPApp> app = getApp(uebkey);
1697                 List<EPRole> roles = getAppRoles(app.get(0).getId());
1698                 List<CentralRole> cenRoleList = new ArrayList<>();
1699                 final Map<String, Long> params = new HashMap<>();
1700                 Integer rolesListAdded = 0;
1701                 try {
1702                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
1703                         ObjectMapper mapper = new ObjectMapper();
1704                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
1705                         String roleList = mapper.writeValueAsString(cenRoleList);
1706                         List<Role> roleObjectList = mapper.readValue(roleList,
1707                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
1708                         for (Role role : roleObjectList) {
1709                                 addRoleInExternalSystem(role, app.get(0));
1710                                 rolesListAdded++;
1711                         }
1712                 } catch (Exception e) {
1713                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
1714                         throw new Exception(e.getMessage());
1715                 }
1716                 return rolesListAdded;
1717         }
1718
1719         /**
1720          * It creating new role in external auth system while doing bulk upload
1721          * 
1722          * @param role
1723          * @param app
1724          * @throws Exception
1725          */
1726         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
1727                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
1728                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1729                 try {
1730                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1731                         template.exchange(
1732                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1733                                         HttpMethod.POST, entity, String.class);
1734                 } catch(HttpClientErrorException e){
1735                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
1736                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1737                 } catch (Exception e) {
1738                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1739                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
1740                         } else {
1741                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
1742                         }
1743                 }
1744         }
1745
1746         @Override
1747         @SuppressWarnings("unchecked")
1748         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
1749                 EPApp app = getApp(uebkey).get(0);
1750                 List<EPRole> roles = getAppRoles(app.getId());
1751                 final Map<String, Long> params = new HashMap<>();
1752                 Integer roleFunctions = 0;
1753                 try {
1754                         for (EPRole role : roles) {
1755                                 params.put("roleId", role.getId());
1756                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
1757                                                 params, null);
1758                                 if (!appRoleFunc.isEmpty()) {
1759                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
1760                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
1761                                                 roleFunctions++;
1762                                         }
1763                                 }
1764                         }
1765                 } catch(HttpClientErrorException e){
1766                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
1767                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1768                 } catch (Exception e) {
1769                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
1770                 }
1771                 return roleFunctions;
1772         }
1773         
1774         /**
1775          * Its adding a role function while doing bulk upload
1776          * 
1777          * @param addRoleFunc
1778          * @param role
1779          * @param app
1780          */
1781         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
1782                 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
1783                 ExternalAccessRolePerms extRolePerms = null;
1784                 ExternalAccessPerms extPerms = null;
1785                 ObjectMapper mapper = new ObjectMapper();
1786                 try {
1787                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1788
1789                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
1790                                         addRoleFunc.getFunctionName());
1791                         extRolePerms = new ExternalAccessRolePerms(extPerms,
1792                                         app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1793                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1794                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1795                         template.exchange(
1796                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
1797                                         HttpMethod.POST, entity, String.class);
1798                 } catch (Exception e) {
1799                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1800                                 logger.error(EELFLoggerDelegate.errorLogger,
1801                                                 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
1802                         } else {
1803                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
1804                                                 e.getMessage());
1805                         }
1806                 }
1807         }
1808
1809         @Override
1810         public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
1811                 EPApp app = getApp(uebkey).get(0);
1812                 CentralRoleFunction cenRoleFunc = null;
1813                 for (RoleFunction roleFunction : roleFunctionsList) {
1814                         cenRoleFunc = new CentralRoleFunction(roleFunction.getCode(), roleFunction.getName());
1815                         addRoleFunctionInExternalSystem(cenRoleFunc, app);
1816                 }
1817         }
1818
1819         @Override
1820         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
1821                 EPApp app = getApp(uebkey).get(0);
1822                 for (Role role : roleList) {
1823                         addRoleInExternalSystem(role, app);
1824                 }
1825         }
1826
1827         @SuppressWarnings("unchecked")
1828         @Override
1829         public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
1830                 EPApp app = getApp(uebkey).get(0);
1831                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1832                 for (Role role : roleList) {
1833                         try {
1834                                 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
1835                                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
1836                                 ObjectMapper roleFunctionsMapper = new ObjectMapper();
1837                                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
1838                                 while (itetaror.hasNext()) {
1839                                         Object nextValue = itetaror.next();
1840                                         RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
1841                                         roleFunctionListNew.add(roleFunction);
1842                                 }
1843                                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
1844                                                 .collect(Collectors.toList());
1845                                 for (RoleFunction roleFunction : listWithoutDuplicates) {
1846                                         String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
1847                                         ExternalAccessRolePerms extRolePerms = null;
1848                                         ExternalAccessPerms extPerms = null;
1849                                         ObjectMapper mapper = new ObjectMapper();
1850                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
1851                                                         "*");
1852                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
1853                                                         app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1854                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1855                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1856                                         template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1857                                                         + "role/perm", HttpMethod.PUT, entity, String.class);
1858                                 }
1859                         } catch (Exception e) {
1860                                 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1861                                         logger.error(EELFLoggerDelegate.errorLogger,
1862                                                         "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
1863                                 } else {
1864                                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
1865                                                         e.getMessage());
1866                                 }
1867                         }
1868
1869                 }
1870         }
1871
1872         @Override
1873         @SuppressWarnings("unchecked")
1874         @Transactional
1875         public void syncApplicationRolesWithEcompDB(EPApp app) {
1876                 try {
1877                         ResponseEntity<String> response = null;
1878                         List<EPRole> finalRoleList = new ArrayList<>();
1879                         ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
1880                         ExternalAccessPerms externalAccessPerms = null;
1881                         List<String> functionCodelist = new ArrayList<>();
1882                         List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
1883                         ObjectMapper mapper = new ObjectMapper();
1884                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1885                         HttpEntity<String> entity = new HttpEntity<>(headers);
1886                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
1887                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1888                         response = template
1889                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1890                                                         + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1891                         String res = response.getBody();
1892                         logger.debug(EELFLoggerDelegate.debugLogger,
1893                                         "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
1894                                         res);
1895                         JSONObject jsonObj = new JSONObject(res);
1896                         JSONArray extRole = jsonObj.getJSONArray("role");
1897                         for (int i = 0; i < extRole.length(); i++) {
1898                                 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
1899                                                 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
1900                                                 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
1901                                                                 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
1902                                         extRole.remove(i);
1903                                         i--;
1904                                 }                       
1905                         }
1906                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
1907                         for (int i = 0; i < extRole.length(); i++) {
1908                                 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
1909                                 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
1910                                 JSONObject Role = (JSONObject) extRole.get(i);
1911                                 if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
1912                                         ApplicationRole.setActive("true");
1913                                         ApplicationRole.setAppId(IS_NULL_STRING);
1914                                         ApplicationRole.setPriority(IS_NULL_STRING);
1915                                         ApplicationRole.setAppRoleId(IS_NULL_STRING);
1916                                         String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
1917                                         ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
1918                                 } else {
1919                                         String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1920                                         ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
1921                                 }
1922
1923                                 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
1924                                 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
1925                                         JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
1926                                         for (int j = 0; j < extPerm.length(); j++) {
1927                                                 JSONObject perms = extPerm.getJSONObject(j);
1928                                                 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
1929                                                                 perms.getString("instance"), perms.getString("action"));
1930                                                 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
1931                                                 functionCodelist.add(ePAppRoleFunction.getCode());
1932                                                 externalAccessPermsOfRole.add(externalAccessPerms);
1933                                         }
1934                                 }
1935
1936                                 if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
1937                                         externalRoleDetail.setActive(false);
1938                                 } else {
1939                                         externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
1940                                 }
1941                                 externalRoleDetail.setName(ApplicationRole.getName());
1942
1943                                 if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
1944                                         externalRoleDetail.setAppId(null);
1945                                 } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
1946                                         externalRoleDetail.setAppId(app.getId());
1947                                 } else {
1948                                         externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
1949                                 }
1950
1951                                 if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
1952                                         externalRoleDetail.setPriority(null);
1953                                 } else {
1954                                         externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
1955                                 }
1956
1957                                 if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
1958                                         externalRoleDetail.setAppRoleId(null);
1959                                 }
1960
1961                                 if (!externalAccessPermsOfRole.isEmpty()) {
1962                                         // Adding functions to roles  
1963                                         for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
1964                                                 try {
1965                                                         logger.debug(EELFLoggerDelegate.debugLogger,
1966                                                                         "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
1967                                                                         externalpermission.getInstance());
1968                                                         List<CentralRoleFunction> roleFunction = null;
1969                                                         roleFunction = dataAccessService.getList(
1970                                                                         CentralRoleFunction.class, " where function_cd = '"
1971                                                                                         + externalpermission.getInstance() + "' and " + APP_ID_EQUALS + app.getId(),
1972                                                                         null, null);
1973                                                         if (roleFunction.isEmpty()) {
1974                                                                 String funcCode = externalpermission.getType()
1975                                                                                 .substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
1976                                                                                 + externalAccessPerms.getInstance();
1977                                                                 roleFunction = dataAccessService.getList(CentralRoleFunction.class,
1978                                                                                 " where function_cd = '" + funcCode + "' and " + APP_ID_EQUALS + app.getId(), null,
1979                                                                                 null);
1980                                                         }
1981                                                         if(!roleFunction.isEmpty()){
1982                                                         EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
1983                                                         apRoleFunction.setAppId(app.getId());
1984                                                         apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
1985                                                         apRoleFunction.setCode(roleFunction.get(0).getCode());
1986                                                         dataAccessService.saveDomainObject(apRoleFunction, null);
1987                                                         }
1988                                                 } catch (Exception e) {
1989                                                         logger.error(EELFLoggerDelegate.errorLogger,
1990                                                                         "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
1991                                                 }
1992                                         }
1993                                 }
1994                                 externalRoleDetailsList.add(externalRoleDetail);
1995                         }
1996                         for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
1997                                 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
1998                                 finalRoleList.add(ecompRole);
1999                         }
2000
2001                         List<EPRole> applicationRolesList = new ArrayList<>();
2002                         applicationRolesList = getAppRoles(app.getId());
2003                         List<String> applicationRoleIdList = new ArrayList<>();
2004                         for (EPRole applicationRole : applicationRolesList) {
2005                                 applicationRoleIdList.add(applicationRole.getName());
2006                         }
2007
2008                         List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2009                         for (EPRole aafRole : finalRoleList) {
2010                                 if (!applicationRoleIdList.contains(aafRole.getName())) {
2011                                         roleListToBeAddInEcompDB.add(aafRole);
2012                                 }
2013                         }
2014
2015                         // Check if roles exits in external Access system and make it inactive
2016                         final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2017                         for (EPRole extrole : finalRoleList) {
2018                                 checkRolesInactive.put(extrole.getName(), extrole);
2019                         }
2020                         for (EPRole role : applicationRolesList) {
2021                                 try {
2022                                         final Map<String, String> extRoleParams = new HashMap<>();
2023                                         List<EPRole> roleList = null;
2024                                         extRoleParams.put("appRoleName", role.getName());
2025                                         if (!checkRolesInactive.containsKey(role.getName())) {
2026                                                 if (app.getId() == 1) {
2027                                                         roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null);
2028                                                 } else {
2029                                                         extRoleParams.put(APP_ID, app.getId().toString());
2030                                                         roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null);
2031                                                 }
2032                                                 EPRole updateRoleInactive = roleList.get(0);
2033                                                 updateRoleInactive.setActive(false);
2034                                                 dataAccessService.saveDomainObject(updateRoleInactive, null);
2035                                         }
2036                                 } catch (Exception e) {
2037                                         logger.error(EELFLoggerDelegate.errorLogger,
2038                                                         "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2039                                 }
2040                         }
2041
2042                         // It checks properties in the external auth system app role description and updates role in local
2043                         for (EPRole roleItem : finalRoleList) {
2044                                 final Map<String, String> roleParams = new HashMap<>();
2045                                 List<EPRole> currentList = null;
2046                                 roleParams.put("appRoleName", roleItem.getName());
2047                                 if (app.getId() == 1) {
2048                                         currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null);
2049                                 } else {
2050                                         roleParams.put(APP_ID, app.getId().toString());
2051                                         currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null);
2052                                 }
2053
2054                                 if (!currentList.isEmpty()) {
2055                                         try {
2056                                                 Boolean aafRoleActive;
2057                                                 Boolean localRoleActive;
2058                                                 boolean result;
2059                                                 aafRoleActive = Boolean.valueOf(roleItem.getActive());
2060                                                 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2061                                                 result = aafRoleActive.equals(localRoleActive);
2062                                                 EPRole updateRole = currentList.get(0);
2063
2064                                                 if (!result) {
2065                                                         updateRole.setActive(roleItem.getActive());
2066                                                         dataAccessService.saveDomainObject(updateRole, null);
2067                                                 }
2068                                                 if (roleItem.getPriority() != null
2069                                                                 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2070                                                         updateRole.setPriority(roleItem.getPriority());
2071                                                         dataAccessService.saveDomainObject(updateRole, null);
2072                                                 }
2073                                         } catch (Exception e) {
2074                                                 logger.error(EELFLoggerDelegate.errorLogger,
2075                                                                 "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2076                                         }
2077                                 }
2078                         }
2079
2080                         EPRole roleToBeAddedInEcompDB = new EPRole();
2081                         for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2082                                 try {
2083                                         roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2084                                         if (app.getId() == 1) {
2085                                                 roleToBeAddedInEcompDB.setAppRoleId(null);
2086                                         }
2087                                         dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2088                                         List<EPRole> getRoleCreatedInSync = null;
2089                                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2090                                                 getRoleCreatedInSync = dataAccessService.getList(EPRole.class,
2091                                                                 WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "' and app_id = "+app.getId(), null, null);
2092                                                 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2093                                                 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2094                                                 dataAccessService.saveDomainObject(epUpdateRole, null);
2095                                         }
2096                                         List<EPRole> roleList = new ArrayList<>();
2097                                         final Map<String, String> params = new HashMap<>();
2098
2099                                         params.put("appRoleName", roleToBeAddedInEcompDB.getName());
2100                                         if (app.getId() == 1) {
2101                                                 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null);
2102                                         } else {
2103                                                 params.put(APP_ID, app.getId().toString());
2104                                                 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null);
2105                                         }
2106                                         EPRole role = roleList.get(0);
2107                                         Role aaFrole = new Role();
2108                                         aaFrole.setId(role.getId());
2109                                         aaFrole.setActive(role.getActive());
2110                                         aaFrole.setPriority(role.getPriority());
2111                                         aaFrole.setName(role.getName());
2112                                         updateRoleInExternalSystem(aaFrole, app);
2113                                 } catch (Exception e) {
2114                                         logger.error(EELFLoggerDelegate.errorLogger,
2115                                                         "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2116                                 }
2117                         }
2118                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2119                 } catch (HttpClientErrorException e) {
2120                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e);
2121                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2122                 } catch (Exception e) {
2123                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2124                 }
2125         }
2126
2127         /**
2128          * 
2129          * It converts from ExternalRoleDetails.class object to EPRole.class object
2130          * 
2131          * @param externalRoleDetails
2132          * @return EPRole object
2133          */
2134         private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2135                 EPRole role = new EPRole();
2136                 role.setActive(externalRoleDetails.isActive());
2137                 role.setAppId(externalRoleDetails.getAppId());
2138                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2139                 role.setName(externalRoleDetails.getName());
2140                 role.setPriority(externalRoleDetails.getPriority());
2141                 return role;
2142         }
2143
2144         @SuppressWarnings("unchecked")
2145         @Override
2146         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2147                 EPApp app = getApp(uebkey).get(0);
2148                 final Map<String, String> params = new HashMap<>();
2149                 params.put("uebKey", app.getUebKey());
2150                 List<BulkUploadUserRoles> userRolesList = null;
2151                 Integer userRolesAdded = 0;
2152                 if (app.getCentralAuth()) {
2153                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2154                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2155                                 addUserRoleInExternalSystem(userRolesUpload);
2156                                 userRolesAdded++;
2157                         }
2158                 }
2159                 return userRolesAdded;
2160         }
2161
2162         /**
2163          * Its adding a user role in external auth system while doing bulk upload 
2164          * 
2165          * @param userRolesUpload
2166          */
2167         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2168                 try {
2169                         String name = "";
2170                         ObjectMapper mapper = new ObjectMapper();
2171                         if (EPCommonSystemProperties
2172                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2173                                 name = userRolesUpload.getOrgUserId()
2174                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2175                         }
2176                         ExternalAccessUser extUser = new ExternalAccessUser(name,
2177                                         userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_"));
2178                         String userRole = mapper.writeValueAsString(extUser);
2179                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2180                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2181                         template.exchange(
2182                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
2183                                         HttpMethod.POST, entity, String.class);
2184                 } catch(HttpClientErrorException e){
2185                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
2186                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2187                 } catch (Exception e) {
2188                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2189                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
2190                         } else {
2191                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e.getMessage());
2192                         }
2193                 }
2194         }
2195
2196         @Override
2197         public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId) throws Exception {
2198                 try {
2199                         String sql = "";
2200                         Query query = null;
2201                         
2202                         //It should delete only when it portal's roleId
2203                         if(appId.equals(PortalConstants.PORTAL_APP_ID)){
2204                         // Delete from fn_role_function
2205                         sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
2206                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2207                         query = localSession.createSQLQuery(sql);
2208                         query.executeUpdate();
2209                         
2210                         // Delete from fn_role_composite
2211                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
2212                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2213                         query = localSession.createSQLQuery(sql);
2214                         query.executeUpdate();
2215                         }
2216                         
2217                         // Delete from ep_app_role_function
2218                         sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
2219                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2220                         query = localSession.createSQLQuery(sql);
2221                         query.executeUpdate();
2222
2223                         // Delete from ep_role_notification
2224                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
2225                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2226                         query = localSession.createSQLQuery(sql);
2227                         query.executeUpdate();
2228                         
2229                         // Delete from fn_user_pseudo_role
2230                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
2231                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2232                         query = localSession.createSQLQuery(sql);
2233                         query.executeUpdate();
2234
2235                         // Delete form EP_WIDGET_CATALOG_ROLE
2236                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
2237                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2238                         query = localSession.createSQLQuery(sql);
2239                         query.executeUpdate();
2240
2241                         // Delete form EP_WIDGET_CATALOG_ROLE
2242                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
2243                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2244                         query = localSession.createSQLQuery(sql);
2245                         query.executeUpdate();
2246
2247                         // Delete form fn_menu_functional_roles
2248                         sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
2249                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2250                         query = localSession.createSQLQuery(sql);
2251                         query.executeUpdate();
2252
2253                 } catch (Exception e) {
2254                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
2255                         throw new Exception("delete Failed" + e.getMessage());
2256                 }
2257
2258         }
2259         
2260         @SuppressWarnings("unchecked")
2261         @Override
2262         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
2263                 List<String> appMenuFunctionsList = null;
2264                 try {
2265                         EPApp app = getApp(uebkey).get(0);
2266                         final Map<String, Long> appParams = new HashMap<>();
2267                         appParams.put(APP_ID, app.getId());
2268                         appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
2269                 } catch (Exception e) {
2270                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
2271                         return appMenuFunctionsList;
2272                 }
2273                 return appMenuFunctionsList;
2274         }
2275
2276         @SuppressWarnings({ "unchecked"})
2277         @Override
2278         public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
2279                 List<String> usersList = new ArrayList<>();
2280                 List<EcompUser> usersfinalList = new ArrayList<>();
2281                 try {
2282                         EPApp app = getApp(uebkey).get(0);
2283                         final Map<String, Long> appParams = new HashMap<>();
2284                         appParams.put("appId", app.getId());
2285                         List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
2286                                         .executeNamedQuery("ApplicationUserRoles", appParams, null);
2287                         for (EcompUserRoles ecompUserRole : userList) {
2288                                 boolean found = false;
2289                                 Set<EcompRole> roles = null;
2290                                 for (EcompUser user : usersfinalList) {
2291                                         if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
2292                                                 EcompRole ecompRole = new EcompRole();
2293                                                 ecompRole.setId(ecompUserRole.getRoleId());
2294                                                 ecompRole.setName(ecompUserRole.getRoleName());
2295                                                 roles = user.getRoles();
2296                                                 roles.add(ecompRole);
2297                                                 user.setRoles(roles);
2298                                                 found = true;
2299                                                 break;
2300                                         }
2301                                 }
2302
2303                                 if (!found) {
2304                                         EcompUser epUser = new EcompUser();
2305                                         epUser.setOrgId(ecompUserRole.getOrgId());
2306                                         epUser.setManagerId(ecompUserRole.getManagerId());
2307                                         epUser.setFirstName(ecompUserRole.getFirstName());
2308                                         epUser.setLastName(ecompUserRole.getLastName());
2309                                         epUser.setPhone(ecompUserRole.getPhone());
2310                                         epUser.setEmail(ecompUserRole.getEmail());
2311                                         epUser.setOrgUserId(ecompUserRole.getOrgUserId());
2312                                         epUser.setOrgCode(ecompUserRole.getOrgCode());
2313                                         epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
2314                                         epUser.setJobTitle(ecompUserRole.getJobTitle());
2315                                         epUser.setLoginId(ecompUserRole.getLoginId());
2316                                         epUser.setActive(true);
2317                                         roles = new HashSet<>();
2318                                         EcompRole ecompRole = new EcompRole();
2319                                         ecompRole.setId(ecompUserRole.getRoleId());
2320                                         ecompRole.setName(ecompUserRole.getRoleName());
2321                                         roles.add(ecompRole);
2322                                         epUser.setRoles(roles);
2323                                         usersfinalList.add(epUser);
2324                                 }
2325                         }
2326                         ObjectMapper mapper = new ObjectMapper();
2327
2328                         for (EcompUser u1 : usersfinalList) {
2329                                 String str = mapper.writeValueAsString(u1);
2330                                 usersList.add(str);
2331                         }
2332                 } catch (Exception e) {
2333                         logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
2334                         throw e;
2335                 }
2336                 return usersfinalList;
2337         }
2338 }