Merge "Sonar Issues for ExternalAppInitializer.java"
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / ExternalAccessRolesServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 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.onap.portalapp.portal.service;
39
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Iterator;
45 import java.util.LinkedHashMap;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Set;
49 import java.util.SortedSet;
50 import java.util.TreeSet;
51 import java.util.regex.Pattern;
52 import java.util.stream.Collectors;
53
54 import org.apache.commons.codec.DecoderException;
55 import org.apache.commons.codec.binary.Hex;
56 import org.apache.commons.lang.StringUtils;
57 import org.hibernate.Query;
58 import org.hibernate.Session;
59 import org.hibernate.SessionFactory;
60 import org.hibernate.Transaction;
61 import org.hibernate.criterion.Criterion;
62 import org.hibernate.criterion.Restrictions;
63 import org.json.JSONArray;
64 import org.json.JSONObject;
65 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
66 import org.onap.portalapp.portal.domain.CentralizedApp;
67 import org.onap.portalapp.portal.domain.EPApp;
68 import org.onap.portalapp.portal.domain.EPAppRoleFunction;
69 import org.onap.portalapp.portal.domain.EPRole;
70 import org.onap.portalapp.portal.domain.EPUser;
71 import org.onap.portalapp.portal.domain.EPUserApp;
72 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
73 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
74 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
75 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
76 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
77 import org.onap.portalapp.portal.exceptions.InvalidUserException;
78 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
79 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
80 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.BulkUploadRoleFunction;
83 import org.onap.portalapp.portal.transport.BulkUploadUserRoles;
84 import org.onap.portalapp.portal.transport.CentralApp;
85 import org.onap.portalapp.portal.transport.CentralRole;
86 import org.onap.portalapp.portal.transport.CentralRoleFunction;
87 import org.onap.portalapp.portal.transport.CentralUser;
88 import org.onap.portalapp.portal.transport.CentralUserApp;
89 import org.onap.portalapp.portal.transport.CentralV2Role;
90 import org.onap.portalapp.portal.transport.CentralV2User;
91 import org.onap.portalapp.portal.transport.CentralV2UserApp;
92 import org.onap.portalapp.portal.transport.EcompUserRoles;
93 import org.onap.portalapp.portal.transport.ExternalAccessPerms;
94 import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail;
95 import org.onap.portalapp.portal.transport.ExternalAccessRole;
96 import org.onap.portalapp.portal.transport.ExternalAccessRolePerms;
97 import org.onap.portalapp.portal.transport.ExternalAccessUser;
98 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
99 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
100 import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction;
101 import org.onap.portalapp.portal.transport.LocalRole;
102 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
103 import org.onap.portalapp.portal.utils.EcompPortalUtils;
104 import org.onap.portalapp.portal.utils.PortalConstants;
105 import org.onap.portalapp.util.EPUserUtils;
106 import org.onap.portalsdk.core.domain.Role;
107 import org.onap.portalsdk.core.domain.RoleFunction;
108 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
109 import org.onap.portalsdk.core.restful.domain.EcompRole;
110 import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
111 import org.onap.portalsdk.core.restful.domain.EcompUser;
112 import org.onap.portalsdk.core.service.DataAccessService;
113 import org.onap.portalsdk.core.util.SystemProperties;
114 import org.springframework.beans.factory.annotation.Autowired;
115 import org.springframework.context.annotation.EnableAspectJAutoProxy;
116 import org.springframework.http.HttpEntity;
117 import org.springframework.http.HttpHeaders;
118 import org.springframework.http.HttpMethod;
119 import org.springframework.http.HttpStatus;
120 import org.springframework.http.ResponseEntity;
121 import org.springframework.stereotype.Service;
122 import org.springframework.transaction.annotation.Transactional;
123 import org.springframework.web.client.HttpClientErrorException;
124 import org.springframework.web.client.RestTemplate;
125
126 import com.fasterxml.jackson.core.JsonProcessingException;
127 import com.fasterxml.jackson.databind.DeserializationFeature;
128 import com.fasterxml.jackson.databind.ObjectMapper;
129 import com.fasterxml.jackson.databind.type.TypeFactory;
130
131 @Service("externalAccessRolesService")
132 @EnableAspectJAutoProxy
133 @EPMetricsLog
134 @EPAuditLog
135 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
136
137         private static final String APP_ROLE_NAME_PARAM = "appRoleName";
138
139         private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
140
141         private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
142
143         private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
144
145         private static final String FUNCTION_CODE_PARAMS = "functionCode";
146
147         private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
148
149         private static final String OWNER = ".owner";
150
151         private static final String ADMIN = ".admin";
152
153         private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
154
155         private static final String FUNCTION_PIPE = "|";
156
157         private static final String IS_NULL_STRING = "null";
158
159         private static final String EXTERNAL_AUTH_PERMS = "perms";
160
161         private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
162
163         private static final String IS_EMPTY_JSON_STRING = "{}";
164
165         private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
166
167         private static final String APP_ROLE_ID = "appRoleId";
168
169         private static final String APP_ID = "appId";
170
171         private static final String PRIORITY = "priority";
172
173         private static final String ACTIVE = "active";
174
175         private static final String ROLE_NAME = "name";
176
177         private static final String ID = "id";
178
179         private static final String APP_ID_EQUALS = " app_id = ";
180         
181         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
182
183         @Autowired
184         private DataAccessService dataAccessService;
185         
186         @Autowired
187         private EPAppService epAppService;
188         
189         @Autowired
190         private SessionFactory sessionFactory;
191         
192         @Autowired
193         EPRoleService ePRoleService;
194
195         RestTemplate template = new RestTemplate();
196         
197         
198         // These decode values are based on HexDecoder
199         static final String decodeValueOfForwardSlash = "2f";
200         static final String decodeValueOfHiphen = "2d";
201         static final String decodeValueOfStar = "2a";
202
203         @SuppressWarnings("unchecked")
204         public List<EPRole> getAppRoles(Long appId) throws Exception {
205                 List<EPRole> applicationRoles = null;
206                 final Map<String, Long> appParams = new HashMap<>();
207                 try {
208                         if (appId == 1) {
209                                 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
210                         } else {
211                                 appParams.put("appId", appId);
212                                 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
213                         }
214                 } catch (Exception e) {
215                         logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
216                         throw e;
217                 }
218                 return applicationRoles;
219         }
220
221         @SuppressWarnings("unchecked")
222         @Override
223         public List<EPApp> getApp(String uebkey) throws Exception {
224                 List<EPApp> app = null;
225                 try {
226                         final Map<String, String> appUebkeyParams = new HashMap<>();
227                         appUebkeyParams.put("appKey", uebkey);
228                         app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
229                         if(!app.isEmpty() && !app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
230                                 throw new InactiveApplicationException("Application:"+app.get(0).getName()+" is Unavailable");
231                         }
232                 } catch (Exception e) {
233                         logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
234                         throw e;
235                 }
236                 return app;
237         }
238
239         /**
240          * It returns  single application role from external auth system 
241          * @param addRole
242          * @param app
243          * @return JSON string which contains application role details
244          * @throws Exception
245          */
246         private String getSingleAppRole(String addRole, EPApp app) throws Exception {
247                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
248                 HttpEntity<String> entity = new HttpEntity<>(headers);
249                 ResponseEntity<String> response = null;
250                 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
251                 response = template.exchange(
252                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
253                                                 + app.getNameSpace()
254                                                 + "." + addRole
255                                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
256                                 HttpMethod.GET, entity, String.class);
257                 logger.debug(EELFLoggerDelegate.debugLogger,
258                                 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
259                                 response.getStatusCode().value());
260                 return response.getBody();
261         }
262
263         @Override
264         public boolean addRole(Role addRole, String uebkey) throws Exception {
265                 boolean response = false;
266                 ResponseEntity<String> addResponse = null;
267                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
268                 EPApp app = getApp(uebkey).get(0);
269                 String newRole = updateExistingRoleInExternalSystem(addRole, app);
270                 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
271                 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
272                 addResponse = template.exchange(
273                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
274                                 HttpMethod.POST, entity, String.class);
275                 if (addResponse.getStatusCode().value() == 201) {
276                         response = true;
277                         logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system  and response code: {} ", addResponse.getStatusCode().value());
278                 }
279                 if (addResponse.getStatusCode().value() == 406) {
280                         logger.error(EELFLoggerDelegate.errorLogger,
281                                         "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
282                 }
283                 return response;
284         }
285
286         /**
287          * 
288          * It deletes record in external auth system
289          * 
290          * @param delRole
291          * @return JSON String which has status code and response body 
292          * @throws Exception
293          */
294         private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
295                 ResponseEntity<String> delResponse = null;
296                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
297                 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
298                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
299                 delResponse = template.exchange(
300                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
301                                 HttpMethod.DELETE, entity, String.class);
302                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", delRole, delResponse.getStatusCode().value());
303                 return delResponse;
304         }
305
306         /**
307          * It updates role in external auth system
308          * 
309          * @param updateExtRole
310          * @param app
311          * @return true if success else false
312          * @throws Exception
313          *                                      If updateRoleInExternalSystem fails we catch it in logger for detail message
314          */
315         @SuppressWarnings("unchecked")
316         private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
317                 boolean response = false;
318                 ObjectMapper mapper = new ObjectMapper();
319                 ResponseEntity<String> deleteResponse = null;
320                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
321                 List<EPRole> epRoleList = null;
322                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
323                                 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
324                         epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
325                 } else {
326                         epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
327                 }
328
329                 // Assigning functions to global role
330                 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
331                         List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
332                         EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
333                         addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
334                         response = true;
335                 } else {
336                         String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
337                         List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
338                         if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
339                                 JSONObject jsonObj = new JSONObject(appRole);
340                                 JSONArray extRole = jsonObj.getJSONArray("role");
341                                 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
342                                         String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
343                                         Map<String, String> delRoleKeyMapper = new HashMap<>();
344                                         delRoleKeyMapper.put(ROLE_NAME, roleName);
345                                         String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
346                                         deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
347                                         if (deleteResponse.getStatusCode().value() != 200) {
348                                                 throw new ExternalAuthSystemException(deleteResponse.getBody());
349                                         }
350                                         addRole(updateExtRole, app.getUebKey());
351                                 } else {
352                                         String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
353                                         String name = extRole.getJSONObject(0).getString(ROLE_NAME);
354                                         List<ExternalAccessPerms> list = new ArrayList<>();
355                                         if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
356                                                 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
357                                                 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
358                                                                 .constructCollectionType(List.class, ExternalAccessPerms.class));
359                                         }
360                                         ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class);
361                                         // If role name or role functions are updated then delete
362                                         // record in External System and add new record to avoid
363                                         // conflicts
364                                         Boolean existingRoleActive;
365                                         boolean isActiveValueChanged;
366                                         // check role active status
367                                         existingRoleActive = new Boolean(sysRoleList.getActive());
368                                         isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive());
369                                         boolean isRoleNameChanged = false;
370                                         if (!sysRoleList.getName().equals(updateExtRole.getName())) {
371                                                 isRoleNameChanged = true;
372                                                 Map<String, String> delRoleKeyMapper = new HashMap<>();
373                                                 delRoleKeyMapper.put(ROLE_NAME, name);
374                                                 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
375                                                 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
376                                                 if (deleteResponse.getStatusCode().value() != 200) {
377                                                         logger.error(EELFLoggerDelegate.errorLogger,
378                                                                         "updateRoleInExternalSystem:  Failed to delete role in external system due to {} ",
379                                                                         deleteResponse.getBody());
380                                                         throw new ExternalAuthSystemException(deleteResponse.getBody());
381                                                 }
382                                                 addRole(updateExtRole, app.getUebKey());
383                                                 // add partner functions to the global role in External Auth System
384                                                 if(!list.isEmpty() && isGlobalRole){
385                                                         addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);       
386                                                 }
387                                                 list.removeIf(perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
388                                                 // if role name is changes please ignore the previous functions in External Auth and update with user requested functions
389                                                 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
390                                                                 list);
391                                         }
392                                         boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),
393                                                         String.valueOf(updateExtRole.getPriority()));
394                                         ExternalAccessRole updateRole = new ExternalAccessRole();
395                                         if (!isActiveValueChanged || !checkPriorityStatus || sysRoleList.getId().equals(IS_NULL_STRING)
396                                                         || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
397                                                 String updateDesc = "";
398                                                 List<EPRole> getRole;
399                                                 final Map<String, String> getAppRoleByName =  new HashMap<>();
400                                                 getAppRoleByName.put(APP_ROLE_NAME_PARAM, updateExtRole.getName());
401                                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
402                                                         getRole = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getAppRoleByName,
403                                                                         null);
404                                                 } else {
405                                                         getAppRoleByName.put("appId", String.valueOf(app.getId()));
406                                                         getRole = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
407                                                                         getAppRoleByName, null);
408                                                 }
409                                                 Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
410                                                 extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId()));
411                                                 extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName()));
412                                                 extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive()));
413                                                 extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority()));
414                                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
415                                                         extSystemUpdateRoleJsonMapper.put(APP_ID, "null");
416                                                         extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null");
417                                                 } else {
418                                                         extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId()));
419                                                         extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID,
420                                                                         String.valueOf(getRole.get(0).getAppRoleId()));
421
422                                                 }
423                                                 updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
424                                                 updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
425                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
426                                                 updateRole.setDescription(updateDesc);
427                                                 String updateRoleDesc = mapper.writeValueAsString(updateRole);
428                                                 HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
429                                                 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for PUT: {}",
430                                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleDesc);
431                                                 ResponseEntity<String> updatePermsResponse = template.exchange(
432                                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
433                                                                                 + "role",
434                                                                 HttpMethod.PUT, entity, String.class);
435                                                 logger.debug(EELFLoggerDelegate.debugLogger,
436                                                                 "updateRoleInExternalSystem: Finished updating in External Auth system {} and status code: {} ",
437                                                                 updateRoleDesc, updatePermsResponse.getStatusCode().value());
438                                         }
439                                         if(!isRoleNameChanged) {
440                                                 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
441                                                                 list);
442                                         }
443                                 }
444                         } else {
445                                 // It seems like role exists in local DB but not in External
446                                 // Access system
447                                 addRole(updateExtRole, app.getUebKey());
448                                 List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
449                                 response = true;
450                                 if (!roleFunctionListUpdate.isEmpty()) {
451                                         addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
452                                 }
453                         }
454                 }
455                 return response;
456         }
457
458         private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
459                         List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
460                 boolean response;
461                 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
462                 for (RoleFunction addPerm : roleFunctionListNew) {
463                         updateRoleFunc.put(addPerm.getCode(), addPerm);
464                 }
465                 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
466                 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
467                 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
468                 // Update permissions in the ExternalAccess System
469                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
470                 if (!list.isEmpty()) {
471                         for (ExternalAccessPerms perm : list) {
472                                 RoleFunction roleFunc =  updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());   
473                                 if (roleFunc==null) {
474                                         RoleFunction roleFuncPipeFilter =  updateRoleFunc.get(perm.getInstance());
475                                         if(roleFuncPipeFilter == null)
476                                         removePermForRole(perm, mapper, name, headers);
477                                 }
478                                 extRolePermMap.put(perm.getInstance(), perm);
479                                 extRolePermMapPipes.put(
480                                                 perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
481                         }
482                 }
483                 response = true;
484                 if (!roleFunctionListNew.isEmpty()) {
485                         for (RoleFunction roleFunc : roleFunctionListNew) {
486                                 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
487                                         ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
488                                         if (perm == null) {
489                                                 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
490                                                                 roleFunc);
491                                         }
492                                 } else {
493                                         if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
494                                                 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
495                                                                 roleFunc);
496                                         }
497                                 }
498                         }
499                 }
500                 return response;
501         }
502         
503         /*
504          * Adds function to the role in the external auth system while editing a role or updating new functions to a role 
505          *
506          */
507         private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
508                         HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
509                 boolean response;
510                 ExternalAccessRolePerms extRolePerms;
511                 ExternalAccessPerms extPerms;
512                 String code = "";
513                 String type = "";
514                 String action = "";
515                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
516                         code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
517                         type = getFunctionCodeType(roleFunc.getCode());
518                         action = getFunctionCodeAction(roleFunc.getCode());
519                 } else {
520                         code = roleFunc.getCode();
521                         type = roleFunc.getCode().contains("menu") ? "menu" : "url";
522                         action = "*";
523                 }
524                 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
525                 extRolePerms = new ExternalAccessRolePerms(extPerms,
526                                 app.getNameSpace() + "."
527                                                 + updateExtRole.getName().replaceAll(
528                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
529                                                                 "_"));
530                 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
531                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
532                 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
533                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
534                 ResponseEntity<String> addResponse = template.exchange(
535                                 SystemProperties.getProperty(
536                                                 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
537                                 HttpMethod.POST, entity, String.class);
538                 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value()!= 409) {
539                         response = false;
540                         logger.debug(EELFLoggerDelegate.debugLogger,
541                                         "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
542                                         addResponse.getStatusCode().getReasonPhrase(),
543                                         addResponse.getStatusCode().value());
544                 } else {
545                         response = true;
546                         logger.debug(EELFLoggerDelegate.debugLogger,
547                                         "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
548                                         updateRolePerms, addResponse.getStatusCode().value());
549                 }
550                 return response;
551         }
552         
553         private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
554                         EPApp app, Role updateExtRole) throws Exception {
555                 for (ExternalAccessPerms perm : permslist) {
556                         if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
557                                 ExternalAccessRolePerms extAddGlobalRolePerms = null;
558                                 ExternalAccessPerms extAddPerms = null;
559                                 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
560                                 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
561                                                 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
562                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
563                                 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
564                                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
565                                 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
566                                 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
567                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
568                                 try {
569                                         ResponseEntity<String> addResponse = template
570                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
571                                                                         + "role/perm", HttpMethod.POST, entity, String.class);
572                                         if (addResponse.getStatusCode().value() != 201) {
573                                                 logger.debug(EELFLoggerDelegate.debugLogger,
574                                                                 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
575                                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
576                                         } else {
577                                                 logger.debug(EELFLoggerDelegate.debugLogger,
578                                                                 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
579                                                                 addResponse.getStatusCode().value());
580                                         }
581                                 } catch (Exception e) {
582                                         logger.error(EELFLoggerDelegate.errorLogger, "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ",
583                                                         addPerms, e);
584                                 }
585                         }
586                 }
587         }
588
589         @SuppressWarnings("unchecked")
590         private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
591                         throws Exception {
592                 try {
593                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
594                         //GET Permissions from External Auth System
595                         JSONArray extPerms = getExtAuthPermissions(app);
596                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
597                         final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
598                         final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
599                         final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
600                         final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
601                         for (ExternalAccessPermsDetail permDetail : permsDetailList) {
602                                 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
603                                 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
604
605                         }
606                         // Add If function does not exists for role in External Auth System
607                         for (RoleFunction roleFunc : roleFunctionListNew) {
608                                 String roleFuncCode = "";
609                                 ExternalAccessPermsDetail permsDetail;
610                                 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
611                                         roleFuncCode = roleFunc.getCode();
612                                         permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
613                                 } else {
614                                         roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
615                                         permsDetail = existingPermsWithRoles.get(roleFuncCode);
616                                 }
617                                 if (null == permsDetail.getRoles() || !permsDetail.getRoles()
618                                                 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE + epRoleList.get(0).getName().replaceAll(
619                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
620                                         addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
621                                 }
622                                 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
623                                 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
624                         }                       
625                         // Delete functions if exists in External Auth System but not in incoming request
626                         final Map<String, Long> epAppRoleFuncParams =  new HashMap<>();
627                         epAppRoleFuncParams.put("requestedAppId", app.getId());
628                         epAppRoleFuncParams.put("roleId",updateExtRole.getId());
629                         List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
630                         for(GlobalRoleWithApplicationRoleFunction globalRoleFunc: globalRoleFunctionList){
631                                 String globalRoleFuncWithoutPipes = "";
632                                 RoleFunction roleFunc = null;
633                                 if(globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
634                                         globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
635                                         roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
636                                 }else {
637                                         globalRoleFuncWithoutPipes  = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
638                                         roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
639                                 }
640                                 if(roleFunc == null){
641                                         ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
642                                         ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), permDetailFromMap.getAction());
643                                         String roleName = portalAppInfo.getNameSpace()+"."+globalRoleFunc.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
644                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
645                                         removePermForRole(perm, mapper, roleName, headers);
646                                 }
647                         }
648                         logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
649                 } catch (Exception e) {
650                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed",e);
651                         throw e;
652                 }
653         }
654
655         private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, ObjectMapper mapper, EPApp app,
656                         EPApp portalAppInfo) throws Exception {
657                 try {
658                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
659                         ExternalAccessRolePerms extAddRolePerms = null;
660                         ExternalAccessPerms extAddPerms = null;
661                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
662                                 String code = "";
663                                 String type = "";
664                                 String action = "";
665                                 if (addFunction.getCode().contains(FUNCTION_PIPE)) {
666                                         code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
667                                         type = getFunctionCodeType(addFunction.getCode());
668                                         action = getFunctionCodeAction(addFunction.getCode());
669                                 } else {
670                                         code = addFunction.getCode();
671                                         type = addFunction.getCode().contains("menu") ? "menu" : "url";
672                                         action = "*";
673                                 }
674                                 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
675                                 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
676                                                 portalAppInfo.getNameSpace() + "." + globalRole.getName().replaceAll(
677                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
678                                 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
679                                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
680                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
681                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
682                                 ResponseEntity<String> addResponse = template
683                                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
684                                                                 + "role/perm", HttpMethod.POST, entity, String.class);
685                                 if (addResponse.getStatusCode().value() != 201) {
686                                         logger.debug(EELFLoggerDelegate.debugLogger,
687                                                         "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
688                                                         addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
689                                 } else {
690                                         logger.debug(EELFLoggerDelegate.debugLogger,
691                                                         "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
692                                                         addResponse.getStatusCode().value());
693                                 }
694                         logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
695                 }catch(Exception e){
696                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed",e);
697                         throw e;
698                 }
699         }
700
701         /**
702          * 
703          * It adds functions to the role in external auth system 
704          * 
705          * @param updateExtRole
706          * @param addPermsMapper
707          * @param app
708          * @return true if success else false
709          * @throws Exception
710          */
711         private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app)
712                         throws Exception {
713                 boolean response = false;
714                 ExternalAccessRolePerms extAddRolePerms = null;
715                 ExternalAccessPerms extAddPerms = null;
716                 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
717                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
718                 for (RoleFunction roleFunc : roleFunctionListAdd) {
719                         String code = "";
720                         String type= "";
721                         String action = "";
722                         if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
723                                 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
724                                 type = getFunctionCodeType(roleFunc.getCode());
725                                 action = getFunctionCodeAction(roleFunc.getCode());
726                         } else {
727                                 code = roleFunc.getCode();
728                                 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
729                                 action = "*";
730                         }
731                         extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
732                         extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
733                                         app.getNameSpace() + "." + updateExtRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
734                         String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
735                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
736                         logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
737                         ResponseEntity<String> addResponse = template.exchange(
738                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
739                                         HttpMethod.POST, entity, String.class);
740                         if (addResponse.getStatusCode().value() != 201) {
741                                 response = false;
742                                 logger.debug(EELFLoggerDelegate.debugLogger,
743                                                 "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
744                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
745                         } else {
746                                 response = true;
747                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value());
748                         }
749                 }
750                 return response;
751         }
752
753         /**
754          * 
755          * It converts list of functions in updateExtRole parameter to the RoleFunction object
756          * 
757          * @param updateExtRole
758          * @return list of functions 
759          */
760         @SuppressWarnings("unchecked")
761         private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
762                 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
763                 List<RoleFunction> roleFunctionList = new ArrayList<>();
764                 ObjectMapper roleFuncMapper = new ObjectMapper();
765                 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
766                 while (itetaror.hasNext()) {
767                         Object nextValue = itetaror.next();
768                         RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
769                         roleFunctionList.add(roleFunction);
770                 }
771                 return roleFunctionList.stream().distinct().collect(Collectors.toList());
772         }
773
774         /**
775          * It delete permissions/functions in the external auth system
776          * 
777          * @param perm
778          * @param permMapper
779          * @param name
780          * @param headers
781          * @throws JsonProcessingException 
782          * @throws Exception
783          */
784         private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
785                         throws ExternalAuthSystemException, JsonProcessingException {
786                 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
787                 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
788                 try{
789                 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
790                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
791                 ResponseEntity<String> deletePermResponse = template
792                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
793                                                 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
794                 if (deletePermResponse.getStatusCode().value() != 200) {
795                         throw new ExternalAuthSystemException(deletePermResponse.getBody());
796                 }
797                 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
798                                 permDetails, deletePermResponse.getStatusCode().value());
799                 } catch(Exception e){
800                         if(e.getMessage().contains("404")){
801                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", permDetails, e.getMessage());                               
802                         } else{
803                                 throw e;
804                         }
805                 }
806         }
807
808         /**
809          * It will create new role in the External Auth System
810          * 
811          * @param newRole
812          * @param app
813          * @return true if successfully added in the system else false
814          * @throws Exception
815          *             If fails to add role in the system
816          */
817         private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception, HttpClientErrorException {
818                 try{
819                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
820                 ObjectMapper mapper = new ObjectMapper();
821                 String addNewRole = "";
822                 ExternalAccessRole extRole = new ExternalAccessRole();
823                 String addDesc = null;
824                 Map<String, String> extSystemJsonMapper = new LinkedHashMap<>();
825                 extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId()));
826                 extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName()));
827                 extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive()));
828                 extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority()));
829                 extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId()));
830                 extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId()));
831                 addDesc = mapper.writeValueAsString(extSystemJsonMapper);
832                 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
833                 extRole.setDescription(addDesc);
834                 addNewRole = mapper.writeValueAsString(extRole);
835                 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
836                 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
837                 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
838                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
839                                 HttpMethod.POST, postEntity, String.class);
840                         if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
841                                 logger.debug(EELFLoggerDelegate.debugLogger,
842                                                 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
843                                                 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
844                         }
845                 }catch(HttpClientErrorException ht){
846                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ newRole.get(0).getId(), null);
847                         logger.error(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}",
848                                         ht);
849                         throw new HttpClientErrorException(ht.getStatusCode());
850                 }
851         }
852
853         /**
854          * 
855          * It updates existing role in the External Auth System
856          * 
857          * @param addRole
858          *            It Contains role information
859          * @param app
860          * @return string which is formatted to match with the external auth system
861          * @throws JsonProcessingException
862          */
863         private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
864                 ObjectMapper mapper = new ObjectMapper();
865                 String addNewRole = "";
866                 ExternalAccessRole extRole = new ExternalAccessRole();
867                 List<EPRole> role = null;
868                 String addDesc = null;
869                 Map<String, String> extSystemUpdateRole = new LinkedHashMap<>();
870                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
871                         role = getPortalAppRoleInfo(addRole.getId());
872                 } else {
873                         role = getPartnerAppRoleInfo(addRole.getId(), app);
874                 }
875                 extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId()));
876                 extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName()));
877                 extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive()));
878                 extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority()));
879                 extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId()));
880                 extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId()));
881                 addDesc = mapper.writeValueAsString(extSystemUpdateRole);
882                 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
883                 extRole.setDescription(addDesc);
884                 addNewRole = mapper.writeValueAsString(extRole);
885                 return addNewRole;
886         }
887
888         /**
889          * It create a role in the external auth system and then in our local 
890          * 
891          * @param addRoleInDB
892          * @param app
893          * @return true else false
894          * @throws Exception
895          */
896         @SuppressWarnings("unchecked")
897         @Transactional(rollbackFor = Exception.class)
898         private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {                
899                 boolean result = false;
900                 EPRole epRole = null;
901                 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
902                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
903                 ObjectMapper mapper = new ObjectMapper();
904                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
905                 while (itetaror.hasNext()) {
906                         Object nextValue = itetaror.next();
907                         RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
908                         roleFunctionListNew.add(roleFunction);
909                 }
910                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
911                 try {
912                         if (addRoleInDB.getId() == null) { // check if it is new role
913                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
914                                         checkIfRoleExitsInExternalSystem(addRoleInDB, app);
915                                 }
916                                 EPRole epRoleNew = new EPRole();
917                                 epRoleNew.setActive(addRoleInDB.getActive());
918                                 epRoleNew.setName(addRoleInDB.getName());
919                                 epRoleNew.setPriority(addRoleInDB.getPriority());
920                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
921                                         epRoleNew.setAppId(null);
922                                 } else {
923                                         epRoleNew.setAppId(app.getId());
924                                 }
925                                 dataAccessService.saveDomainObject(epRoleNew, null);
926                                 List<EPRole> getRoleCreated = null;
927                                 final Map<String, String> epAppRoleParams =  new HashMap<>();
928                                 final Map<String, String> epAppPortalRoleParams =  new HashMap<>();
929                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
930                                         epAppRoleParams.put("appId", String.valueOf(app.getId()));
931                                         epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
932                                         List<EPRole> roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
933                                         EPRole epUpdateRole = roleCreated.get(0);
934                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
935                                         dataAccessService.saveDomainObject(epUpdateRole, null);
936                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
937                                 } else {
938                                         epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
939                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null);
940                                 }
941                                 // Add role in External Auth system
942                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
943                                         addNewRoleInExternalSystem(getRoleCreated, app);
944                                 }
945                         } else { // if role already exists then update it
946                                 EPRole globalRole = null;
947                                 List<EPRole> applicationRoles;
948                                 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
949                                 boolean isGlobalRole = false;
950                                 if (!globalRoleList.isEmpty()) {
951                                         EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
952                                                         .orElse(null);
953                                         if (role != null) {
954                                                 globalRole = role;
955                                                 isGlobalRole = true;
956                                         }
957                                 }
958                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
959                                                 || (globalRole != null && app.getId() != globalRole.getAppId())) {
960                                         applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
961                                 } else {
962                                         applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
963                                 }
964                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
965                                         updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
966                                         // Add all user to the re-named role in external auth system
967                                         if (!applicationRoles.isEmpty()
968                                                         && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
969                                                 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
970                                                                 addRoleInDB.getName());
971                                         }
972                                 }
973                                 deleteRoleFunction(app, applicationRoles);
974                                 if (!applicationRoles.isEmpty()) {
975                                         epRole = applicationRoles.get(0);
976                                         epRole.setName(addRoleInDB.getName());
977                                         epRole.setPriority(addRoleInDB.getPriority());
978                                         epRole.setActive(addRoleInDB.getActive());
979                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
980                                                 epRole.setAppId(null);
981                                                 epRole.setAppRoleId(null);
982                                         } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
983                                                         && applicationRoles.get(0).getAppRoleId() == null) {
984                                                 epRole.setAppRoleId(epRole.getId());
985                                         }
986                                         dataAccessService.saveDomainObject(epRole, null);
987                                 }
988                                 Long roleAppId = null;
989                                 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
990                                         roleAppId = PortalConstants.PORTAL_APP_ID;
991                                 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
992                                 result = true;
993                         }
994                 } catch (Exception e) {
995                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
996                         throw e;
997                 }
998                 return result;
999         }
1000
1001         /**
1002          * 
1003          * It validates whether role exists in external auth system
1004          * 
1005          * @param checkRole
1006          * @param app
1007          * @throws Exception
1008          *                                      If role exits
1009          */
1010         private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
1011                 getNameSpaceIfExists(app);
1012                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1013                 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
1014                 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
1015                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1016                 ResponseEntity<String> checkRoleInExternalSystem = template
1017                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
1018                                                 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
1019                 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
1020                         logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
1021                         throw new ExternalAuthSystemException(" Role already exists in external system");
1022                 }
1023         }
1024
1025         /**
1026          * It saves list of functions to the role in portal
1027          * 
1028          * @param roleFunctionListNew
1029          * @param app
1030          * @param applicationRoles
1031          * @throws Exception
1032          */
1033         @SuppressWarnings("unchecked")
1034         private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
1035                         throws Exception {      
1036                 final Map<String, String> getAppFunctionParams = new HashMap<>(); 
1037
1038                 for (RoleFunction roleFunc : roleFunctionListNew) {
1039                         String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1040                         EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
1041                         appRoleFunc.setAppId(app.getId());
1042                         appRoleFunc.setRoleId(applicationRoles.get(0).getId());
1043                         appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
1044                         getAppFunctionParams.put("appId", String.valueOf(app.getId()));
1045                         getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
1046                         // query to check if function code has pipes
1047                         List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
1048                         if(roleFunction.isEmpty()){
1049                                 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
1050                                 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
1051                         }
1052                         if(roleFunction.size() > 1){
1053                                 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
1054                                 appRoleFunc.setCode(getExactFunctionCode.getCode());
1055                         } else{
1056                                 appRoleFunc.setCode(roleFunction.get(0).getCode());
1057                         }
1058                         
1059                         dataAccessService.saveDomainObject(appRoleFunc, null);
1060                 }
1061         }
1062
1063         /**
1064          * 
1065          * It filters the app functions which starts with similar name in the result set
1066          * 
1067          * @param roleFunc
1068          * @param roleFunction
1069          * @return CentralRoleFunction 
1070          */
1071         private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
1072                 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>(); 
1073                 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>(); 
1074                 CentralV2RoleFunction getExactFunctionCode = null;
1075                 for(CentralV2RoleFunction cenRoleFunction : roleFunction){
1076                         appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
1077                         appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
1078                 }
1079                 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
1080                 if(getExactFunctionCode == null){
1081                         getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
1082                 }
1083                 return getExactFunctionCode;
1084         }
1085         
1086         /**
1087          * It deletes all EPAppRoleFunction records in the portal
1088          * 
1089          * @param app
1090          * @param role
1091          */
1092         @SuppressWarnings("unchecked")
1093         private void deleteRoleFunction(EPApp app, List<EPRole> role) {
1094                 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
1095                 appRoleFuncsParams.put("appId", app.getId());
1096                 appRoleFuncsParams.put("roleId", role.get(0).getId());
1097                 List<EPAppRoleFunction> appRoleFunctionList =  dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
1098                 if (!appRoleFunctionList.isEmpty()) {
1099                         for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
1100                                 dataAccessService.deleteDomainObject(approleFunction, null);
1101                         }
1102                 }
1103         }
1104         
1105         @Override
1106         @SuppressWarnings("unchecked")
1107         public List<EPUser> getUser(String loginId) throws InvalidUserException{
1108                 final Map<String, String> userParams = new HashMap<>();
1109                 userParams.put("org_user_id", loginId);
1110                 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
1111                 if (userList.isEmpty()) {
1112                         throw new InvalidUserException("User not found");
1113                 }
1114                 return userList;
1115         }
1116
1117         @Override
1118         public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1119                 final Map<String, String> params = new HashMap<>();
1120                 List<EPUser> userList = null;
1121                 CentralV2User cenV2User = null;
1122                 String result = null;
1123                 try {
1124                         params.put("orgUserIdValue", loginId);
1125                         List<EPApp> appList = getApp(uebkey);
1126                         if (!appList.isEmpty()) {
1127                                 userList = getUser(loginId);
1128                                 if (!userList.isEmpty()) {
1129                                         ObjectMapper mapper = new ObjectMapper();
1130                                         cenV2User = getV2UserAppRoles(loginId, uebkey);
1131                                         result = mapper.writeValueAsString(cenV2User);
1132                                 } else if (userList.isEmpty()) {
1133                                         throw new InvalidUserException("User not found");
1134                                 }
1135                         } else {
1136                                 throw new InactiveApplicationException("Application not found");
1137                         }
1138                 } catch (Exception e) {
1139                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1140                         throw e;
1141                 }
1142                 return result;
1143         }
1144
1145         @Override
1146         public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1147                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1148                 List<CentralV2Role> roleList = new ArrayList<>();
1149                 final Map<String, Long> params = new HashMap<>();
1150                 try {
1151                         List<EPApp> app = getApp(uebkey);
1152                         List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1153                         roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1154                         if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
1155                             List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1156                                 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1157                             List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1158                                 if (!globalRolesList.isEmpty()) {
1159                                         for (EPRole eprole : globalRolesList) {
1160                                                 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1161                                                 portalsGlobalRolesFinlaList.add(cenRole);
1162                                         }
1163                                         roleList.addAll(globalRoleList);
1164                                         for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1165                                                 CentralV2Role result = roleList.stream()
1166                                                                         .filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
1167                                                         if (result == null)
1168                                                                 roleList.add(role);
1169                                         }
1170                                 } else {
1171                                         for (EPRole role : globalRolesList) {
1172                                                 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1173                                                 roleList.add(cenRole);
1174                                         }
1175                                 }
1176                         }
1177                 } catch (Exception e) {
1178                         logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1179                         throw e;
1180                 }
1181                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1182                 return roleList.stream().distinct().collect(Collectors.toList());
1183         }
1184
1185         @SuppressWarnings("unchecked")
1186         @Override
1187         public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1188                 EPApp app = getApp(uebkey).get(0);
1189                 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1190                 final Map<String, Long> params = new HashMap<>();
1191                 params.put(APP_ID, app.getId());
1192                 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
1193                 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1194                         String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1195                         String type = getFunctionCodeType(roleFuncItem.getCode());
1196                         String action = getFunctionCodeAction(roleFuncItem.getCode());
1197                         roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1198                         roleFuncItem.setType(type);
1199                         roleFuncItem.setAction(action);
1200                         finalRoleList.add(roleFuncItem);
1201                 }
1202                 return finalRoleList;
1203         }
1204
1205
1206         @Override
1207         public String getFunctionCodeAction(String roleFuncItem) {
1208                 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
1209                                 : EcompPortalUtils.getFunctionAction(roleFuncItem);
1210         }
1211
1212         @Override
1213         public String getFunctionCodeType(String roleFuncItem) {
1214                 String type = null;
1215                 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1216                                 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1217                         type = "menu";
1218                 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
1219                                 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1220                                 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1221                         type = "url";
1222                 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1223                                 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1224                         type = EcompPortalUtils.getFunctionType(roleFuncItem);
1225                 }
1226                 return type;
1227         }
1228
1229         /**
1230          * 
1231          * It check whether function code has no pipes and no url string in it
1232          * 
1233          * @param roleFuncItem
1234          * @return true or false
1235          */
1236         private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1237                 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1238         }
1239         
1240         /**
1241          * 
1242          * It check whether function code has pipes and url string in it  
1243          * 
1244          * @param roleFuncItem
1245          * @return true or false
1246          */
1247         private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1248                 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1249         }
1250
1251         /**
1252          * 
1253          * It check whether function code has no pipes and has url string in it 
1254          * 
1255          * @param roleFuncItem
1256          * @return true or false
1257          */
1258         private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1259                 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1260         }
1261
1262         /**
1263          * It returns user detail information which is deep copy of EPUser.class object
1264          * 
1265          * @param userInfo
1266          * @param userAppSet
1267          * @param app
1268          * @return
1269          * @throws Exception
1270          */
1271         @SuppressWarnings("unchecked")
1272         private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1273
1274                 final Map<String, Long> params = new HashMap<>();
1275                 CentralV2User userAppList = new CentralV2User();
1276                 CentralV2User user1 = null;
1277                 final Map<String, Long> params1 = new HashMap<>();
1278                 List<EPRole> globalRoleList = new ArrayList<>();
1279
1280                 try {
1281                         if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1282                                 params1.put("userId", userInfo.getId());
1283                                 params1.put("appId", app.getId());
1284                                 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1285                         }
1286                         userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1287                         for (EPUserApp userApp : userAppSet) {
1288                                 if (userApp.getRole().getActive()) {
1289                                         EPApp epApp = userApp.getApp();
1290                                         String globalRole = userApp.getRole().getName().toLowerCase();
1291                                         if (((epApp.getId().equals(app.getId()))
1292                                                         && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1293                                                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1294                                                                         && (globalRole.toLowerCase().startsWith("global_")))) {
1295                                                 CentralV2UserApp cua = new CentralV2UserApp();
1296                                                 cua.setUserId(null);
1297                                                 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1298                                                                 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1299                                                                 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1300                                                                 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1301                                                                 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1302                                                                 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1303                                                                 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1304                                                                 epApp.getUebTopicName());
1305                                                 cua.setApp(cenApp);
1306                                                 Long appId = null;
1307                                                 if (globalRole.toLowerCase().startsWith("global_")
1308                                                                 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1309                                                                 && !epApp.getId().equals(app.getId())) {
1310                                                         appId = app.getId();
1311                                                         EPRole result = null;
1312                                                         if (globalRoleList.size() > 0)
1313                                                                 result = globalRoleList.stream()
1314                                                                                 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1315                                                                                 .orElse(null);
1316                                                         if (result == null)
1317                                                                 continue;
1318                                                 } else {
1319                                                         appId = userApp.getApp().getId();
1320                                                 }
1321                                                 params.put("roleId", userApp.getRole().getId());
1322                                                 params.put(APP_ID, appId);
1323                                                 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1324                                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
1325                                                 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1326                                                 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1327                                                         String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1328                                                         String type = getFunctionCodeType(roleFunc.getCode());
1329                                                         String action = getFunctionCodeAction(roleFunc.getCode());
1330                                                         CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1331                                                                         functionCode, roleFunc.getName(), null, type, action, null);
1332                                                         roleFunctionSet.add(cenRoleFunc);
1333                                                 }
1334                                                 Long userRoleId = null;
1335                                                 if (globalRole.toLowerCase().startsWith("global_")
1336                                                                 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1337                                                         userRoleId = userApp.getRole().getId();
1338                                                 } else {
1339                                                         userRoleId = userApp.getRole().getAppRoleId();
1340                                                 }
1341                                                 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1342                                                                 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1343                                                                 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1344                                                                 userApp.getRole().getName(), userApp.getRole().getActive(),
1345                                                                 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1346                                                 cua.setRole(cenRole);
1347
1348                                                 userAppList.getUserApps().add(cua);
1349                                         }
1350                                 }
1351                         }
1352
1353                         user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1354                                         userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1355                                         userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1356                                         userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1357                                         userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1358                                         userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1359                                         userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1360                                         userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1361                                         userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1362                                         userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1363                                         userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1364                                         userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1365                                         userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1366                                         userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1367                                         userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1368                 } catch (Exception e) {
1369                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1370                         throw e;
1371                 }
1372                 return user1;
1373         }
1374
1375         @Override
1376         public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1377                 final Map<String, Long> params = new HashMap<>();
1378                 List<CentralV2Role> roleList = new ArrayList<>();
1379                 CentralV2Role cenRole = new CentralV2Role();
1380                 List<EPRole> roleInfo = null;
1381                 List<EPApp> app = null;
1382                 try {
1383                         app = getApp(uebkey);
1384                         if (app.isEmpty()) {
1385                                 throw new InactiveApplicationException("Application not found");
1386                         }
1387                         if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1388                                 List<EPRole> globalRoleList = new ArrayList<>();
1389                                 globalRoleList = getGlobalRolesOfPortal();
1390                                 if (globalRoleList.size() > 0) {
1391                                         EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1392                                                         .orElse(null);
1393                                         if (result != null)
1394                                                 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1395                                 }
1396                         }
1397                         if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1398                                 roleInfo = getPortalAppRoleInfo(roleId);
1399                         } else {
1400                                 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1401                         }
1402                         roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1403                         if (roleList.isEmpty()) {
1404                                 return cenRole;
1405                         }
1406
1407                 } catch (Exception e) {
1408                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1409                         throw e;
1410
1411                 }
1412                 return roleList.get(0);
1413         }
1414
1415         @SuppressWarnings("unchecked")
1416         private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1417                 List<EPRole> roleInfo;
1418                 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1419                 getPartnerAppRoleParams.put("appRoleId", roleId);
1420                 getPartnerAppRoleParams.put("appId", app.getId());                              
1421                 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1422                 if(roleInfo.isEmpty()) {
1423                         getPartnerAppRoleParams.put("appRoleId", roleId);
1424                         roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1425                 }
1426                 return roleInfo;
1427         }
1428
1429         @SuppressWarnings("unchecked")
1430         private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1431                 List<EPRole> roleInfo;
1432                 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1433                 getPortalAppRoleParams.put("roleId", roleId);
1434                 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1435                 return roleInfo;
1436         }
1437         
1438         /**
1439          * 
1440          * It returns list of app roles along with role functions and which went through deep copy
1441          * 
1442          * @param app
1443          * @param roleInfo
1444          * @param roleList
1445          * @param params
1446          * @return
1447          * @throws DecoderException 
1448          */
1449         @SuppressWarnings("unchecked")
1450         private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1451                         List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1452                 for (EPRole role : roleInfo) {
1453                         params.put("roleId", role.getId());
1454                         params.put(APP_ID, app.get(0).getId());
1455                         List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1456                                         params, null);
1457                         SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1458                         for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1459                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1460                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1461                                 String type = getFunctionCodeType(roleFunc.getCode());
1462                                 String action = getFunctionCodeAction(roleFunc.getCode());
1463                                 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1464                                                 roleFunc.getName(), null, type, action, null);
1465                                 roleFunctionSet.add(cenRoleFunc);
1466                         }
1467                         SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1468                         SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1469                         CentralV2Role cenRole = null;
1470                         if (role.getAppRoleId() == null) {
1471                                 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1472                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1473                                                 roleFunctionSet, childRoles, parentRoles);
1474                         } else {
1475                                 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1476                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1477                                                 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1478                         }
1479                         roleList.add(cenRole);
1480                 }
1481                 return roleList;
1482         }
1483
1484         @SuppressWarnings("unchecked")
1485         @Override
1486         public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1487                 String code = EcompPortalUtils.getFunctionCode(functionCode);
1488                 String encodedCode = encodeFunctionCode(code);
1489                 CentralV2RoleFunction roleFunc = null;
1490                 EPApp app = getApp(uebkey).get(0);
1491                 List<CentralV2RoleFunction> getRoleFuncList = null;
1492                 final Map<String, String> params = new HashMap<>();
1493                 try {
1494                         params.put(FUNCTION_CODE_PARAMS, functionCode);
1495                         params.put(APP_ID, String.valueOf(app.getId()));
1496                         getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1497                         if (getRoleFuncList.isEmpty()) {
1498                                 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1499                                 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1500                                 if (getRoleFuncList.isEmpty()) {
1501                                         return roleFunc;
1502                                 }
1503                         }
1504                         if (getRoleFuncList.size() > 1) {
1505                                 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1506                                 if (cenV2RoleFunction == null)
1507                                         return roleFunc;
1508                                 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1509                         } else {
1510                                 // Check even if single record have pipes
1511                                 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1512                                         roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1513                                 } else {
1514                                         roleFunc = getRoleFuncList.get(0);
1515                                 }
1516                         }
1517                 } catch (Exception e) {
1518                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1519                         throw e;
1520                 }
1521                 return roleFunc;
1522         }
1523
1524         private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1525                 CentralV2RoleFunction roleFunc;
1526                 String functionCodeFormat = getRoleFuncList.getCode();
1527                 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1528                         String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1529                         String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1530                         String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1531                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1532                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
1533                                         getRoleFuncList.getEditUrl());
1534                 } else {
1535                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
1536                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(),
1537                                         getRoleFuncList.getEditUrl());
1538                 }
1539                 return roleFunc;
1540         }
1541
1542         @Override
1543         public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1544                 boolean saveOrUpdateFunction = false;
1545                 try {
1546                         domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
1547                         final Map<String, String> functionParams = new HashMap<>();
1548                         functionParams.put("appId", String.valueOf(app.getId()));
1549                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1550                                 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);                        
1551                         }
1552                         if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
1553                                 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
1554                                         FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
1555                         }
1556                         domainCentralRoleFunction.setAppId(app.getId());
1557                         dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1558                         saveOrUpdateFunction = true;
1559                 } catch (Exception e) {
1560                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1561                         throw e;
1562                 }
1563                 return saveOrUpdateFunction;
1564         }
1565         
1566         /**
1567          * It creates application permission in external auth system
1568          * 
1569          * @param domainCentralRoleFunction
1570          * @param app
1571          * @throws Exception
1572          */
1573         private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1574                         throws Exception {
1575                 ObjectMapper mapper = new ObjectMapper();
1576                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1577                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); 
1578                 String type = "";
1579                 String instance = "";
1580                 String action = "";
1581                 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1582                         type =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType(); 
1583                         instance =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ?  EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
1584                         action =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
1585                 } else{
1586                         type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1587                         instance = domainCentralRoleFunction.getCode();
1588                         action = "*"; 
1589                 }               
1590                 // get Permissions from External Auth System
1591                 JSONArray extPermsList = getExtAuthPermissions(app);
1592                 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1593                 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
1594                 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1595                 if (!checkIfFunctionsExits) {
1596                         try {
1597                                 extPerms.setAction(action);
1598                                 extPerms.setInstance(instance);
1599                                 extPerms.setType(app.getNameSpace() + "." + type);
1600                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1601                                 String addFunction = mapper.writeValueAsString(extPerms);
1602                                 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1603                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1604                                 ResponseEntity<String> addPermResponse= template.exchange(
1605                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1606                                                 HttpMethod.POST, entity, String.class);
1607                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
1608                         } catch(HttpClientErrorException e){
1609                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1610                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1611                                 throw e;
1612                         }catch (Exception e) {
1613                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1614                                                 e);
1615                                 throw e;
1616                         }
1617                 } else {
1618                         try {
1619                                 extPerms.setAction(action);
1620                                 extPerms.setInstance(instance);
1621                                 extPerms.setType(app.getNameSpace() + "." + type);
1622                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1623                                 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1624                                 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1625                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1626                                 ResponseEntity<String> updatePermResponse = template.exchange(
1627                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1628                                                 HttpMethod.PUT, entity, String.class);
1629                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
1630                         } catch(HttpClientErrorException e){
1631                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1632                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1633                                 throw e;
1634                         } catch (Exception e) {
1635                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
1636                                 throw e;
1637                         }
1638                 }
1639         }
1640
1641         @SuppressWarnings("unchecked")
1642         @Override
1643         @Transactional(rollbackFor = Exception.class)
1644         public boolean deleteCentralRoleFunction(String code, EPApp app) {
1645                 boolean deleteFunctionResponse = false;
1646                 try {
1647                         final Map<String, String> params = new HashMap<>();
1648                         params.put(FUNCTION_CODE_PARAMS, code);
1649                         params.put(APP_ID, String.valueOf(app.getId()));
1650                         List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1651                                         .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1652                         CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1653                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1654                                 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1655                                 // Delete role function dependency records
1656                                 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1657                         }
1658                         dataAccessService.deleteDomainObject(appFunctionCode, null);
1659                         deleteFunctionResponse = true;
1660                 } catch (Exception e) {
1661                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1662                 }
1663                 return deleteFunctionResponse;
1664         }
1665
1666         /**
1667          * It deletes app function record in portal 
1668          * 
1669          * @param code
1670          * @param app
1671          */
1672         private void deleteAppRoleFunctions(String code, EPApp app) {
1673                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1674                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1675         }
1676         
1677         /**
1678          * 
1679          * It deletes permission in the external auth system  
1680          * 
1681          * @param domainCentralRoleFunction
1682          * @param app
1683          * @throws Exception
1684          */
1685         private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1686                         throws Exception {
1687                 try {
1688                         ObjectMapper mapper = new ObjectMapper();
1689                         ExternalAccessPerms extPerms = new ExternalAccessPerms();
1690                         String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1691                         String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1692                         String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1693                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1694                         extPerms.setAction(actionValue);
1695                         extPerms.setInstance(instanceValue);
1696                         extPerms.setType(app.getNameSpace() + "." + checkType);
1697                         extPerms.setDescription(domainCentralRoleFunction.getName());
1698                         String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1699                         HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1700                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1701                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1702                         ResponseEntity<String> delPermResponse = template
1703                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1704                                                         + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1705                         logger.debug(EELFLoggerDelegate.debugLogger,
1706                                         "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1707                                         deleteRoleFunction, delPermResponse.getStatusCode().value());
1708                 } catch(HttpClientErrorException e){
1709                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1710                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1711                 } catch (Exception e) {
1712                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1713                                 logger.debug(EELFLoggerDelegate.debugLogger,
1714                                                 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
1715                                                 e.getMessage());
1716                         } else {
1717                                 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1718                         }
1719                 }
1720         }
1721
1722         @Override
1723         public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1724                 boolean response = false;
1725                 String message = "";
1726                 try {
1727                         EPApp app = getApp(uebkey).get(0);
1728                         addRoleInEcompDB(saveRole, app);
1729                         response = true;
1730                 } catch (Exception e) {
1731                         message = e.getMessage();
1732                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1733                 }
1734                 return new ExternalRequestFieldsValidator(response,message);
1735         }
1736
1737         @SuppressWarnings("unchecked")
1738         @Override
1739         public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1740                 Session localSession = sessionFactory.openSession();
1741                 Transaction transaction = null;
1742                 boolean result = false;
1743                 try {
1744                         List<EPRole> epRoleList = null;
1745                         EPApp app = getApp(uebkey).get(0);
1746                         final Map<String, String> deleteRoleParams = new HashMap<>();
1747                         deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1748                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1749                                 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1750                         } else {
1751                                 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1752                                 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
1753                         }
1754                         if (!epRoleList.isEmpty()) {
1755                                 transaction = localSession.beginTransaction();
1756                                 // Delete app role functions before deleting role
1757                                 deleteRoleFunction(app, epRoleList);
1758                                 if (app.getId() == 1) {
1759                                         // Delete fn_user_ role
1760                                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1761                                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1762                                         boolean isPortalRequest = false;
1763                                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1764                                 }
1765                                 deleteRoleInExternalAuthSystem(epRoleList, app);
1766                                 transaction.commit();
1767                                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1768                                 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1769                         }
1770                         result = true;
1771                 } catch (Exception e) {
1772                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1773                         result = false;
1774                 } finally {
1775                         localSession.close();
1776                 }
1777                 return result;
1778         }
1779         
1780         /**
1781          * 
1782          * It deletes role for application in external auth system 
1783          * 
1784          * @param epRoleList contains role information
1785          * @param app contains application information
1786          * @throws Exception
1787          */
1788         private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1789                 ResponseEntity<String> deleteResponse;
1790                 ResponseEntity<String> res = getNameSpaceIfExists(app);
1791                 if (res.getStatusCode() == HttpStatus.OK) {
1792                 // Delete Role in External System
1793                 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1794                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1795                 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1796                 if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1797                         EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1798                         logger.error(EELFLoggerDelegate.errorLogger,
1799                                         "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1800                                         deleteResponse.getBody());
1801                 }
1802                 logger.debug(EELFLoggerDelegate.debugLogger,
1803                                 "deleteRoleForApplication: about to commit the transaction");
1804                 }
1805         }
1806
1807         /**
1808          * 
1809          * It deletes application user role in external auth system
1810          * 
1811          * @param role
1812          * @param app
1813          * @param LoginId
1814          * @throws Exception
1815          */
1816         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1817                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1818                 HttpEntity<String> entity = new HttpEntity<>(headers);
1819                 getNameSpaceIfExists(app);
1820                 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1821                 ResponseEntity<String> getResponse = template
1822                                 .exchange(
1823                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1824                                                                 + LoginId
1825                                                                 + SystemProperties
1826                                                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1827                                                                 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1828                                                 HttpMethod.GET, entity, String.class);
1829                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1830                 if (getResponse.getStatusCode().value() != 200) {
1831                         throw new ExternalAuthSystemException(getResponse.getBody());
1832                 }
1833                 String res = getResponse.getBody();
1834                 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1835                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1836                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1837                         ResponseEntity<String> deleteResponse = template
1838                                         .exchange(
1839                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1840                                                                         + "userRole/" + LoginId
1841                                                                         + SystemProperties
1842                                                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1843                                                                         + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1844                                                         HttpMethod.DELETE, userRoleentity, String.class);
1845                         if (deleteResponse.getStatusCode().value() != 200) {
1846                                 throw new ExternalAuthSystemException("Failed to delete user role");
1847                         }
1848                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1849                 }
1850         }
1851
1852         @SuppressWarnings("unchecked")
1853         @Override
1854         public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1855                 List<CentralV2Role> roleList = new ArrayList<>();
1856                 try {
1857                         List<EPApp> app = getApp(uebkey);
1858                         final Map<String, Long> params = new HashMap<>();
1859                         // check if portal
1860                         Long appId = null;
1861                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1862                                 appId = app.get(0).getId();
1863                         }
1864                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
1865                         Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1866                         Criterion appIdCrt;
1867                         if (appId == null)
1868                                 appIdCrt = Restrictions.isNull("appId");
1869                         else
1870                                 appIdCrt = Restrictions.eq("appId", appId);
1871                         Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1872                         restrictionsList.add(andCrit);
1873                         List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1874                         roleList = createCentralRoleObject(app, epRole, roleList, params);
1875                         List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1876                         if (globalRoleList.size() > 0)
1877                                 roleList.addAll(globalRoleList);
1878                 } catch (Exception e) {
1879                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1880                         throw e;
1881                 }
1882                 return roleList;
1883
1884         }
1885
1886         @Override
1887         @Transactional(rollbackFor = Exception.class)
1888         public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1889                 Session localSession = sessionFactory.openSession();
1890                 String message = "";
1891                 Transaction transaction = null;
1892                 boolean response = false;
1893                 EPApp app = null;
1894                 try {
1895                         transaction = localSession.beginTransaction();
1896                         List<EPRole> epRoleList = null;
1897                         app = getApp(uebkey).get(0);
1898                         if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1899                                 epRoleList = getPortalAppRoleInfo(roleId);
1900                         } else{
1901                                 epRoleList = getPartnerAppRoleInfo(roleId, app);
1902                         }
1903                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1904                                 // Delete User Role in External System before deleting role
1905                                 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);        
1906                         }
1907                         // Delete user app roles
1908                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1909                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1910                         boolean isPortalRequest = false;
1911                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1912                         transaction.commit();
1913                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1914                                 // Final call to delete role once all dependencies has been deleted
1915                                 deleteRoleInExternalAuthSystem(epRoleList, app);
1916                         }
1917                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);            
1918                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1919                         response = true;
1920                 } catch(HttpClientErrorException e){
1921                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1922                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1923                         message = e.getMessage();
1924                 } catch (Exception e) {
1925                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1926                         EcompPortalUtils.rollbackTransaction(transaction,
1927                                         "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1928                         message = e.getMessage();
1929                 } finally {
1930                         localSession.close();
1931                 }
1932                 return new ExternalRequestFieldsValidator(response,message);
1933         }
1934         
1935         @Override
1936         @SuppressWarnings("unchecked")
1937         @Transactional
1938         public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1939                 try {
1940
1941                         // get Permissions from External Auth System
1942                         JSONArray extPerms = getExtAuthPermissions(app);
1943                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1944
1945                         // get functions in DB
1946                         final Map<String, Long> params = new HashMap<>();
1947                         final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1948                         params.put(APP_ID, app.getId());
1949                         List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1950                                         null);
1951                         if (!appFunctions.isEmpty()) {
1952                                 for (CentralV2RoleFunction roleFunc : appFunctions) {
1953                                         roleFuncMap.put(roleFunc.getCode(), roleFunc);
1954                                 }
1955                         }
1956                         
1957                         // get Roles for portal in DB
1958                         List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1959                         final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1960                         for(EPRole epRole : portalRoleList){
1961                                 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1962                         }
1963                         
1964                         // get Roles in DB
1965                         final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
1966                         
1967                         // store External Permissions with Pipe and without Pipe (just instance)
1968                         final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1969                         final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1970                         for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1971                                 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1972                                 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1973                                 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1974                         }
1975
1976                         // Add if new functions and app role functions were added in
1977                         // external auth system
1978                         for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1979                                 String code = permsDetail.getInstance();
1980                                 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1981                                 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1982                                                 getFunctionCodeKey);
1983                                 List<String> roles = permsDetail.getRoles();
1984                                 if (roles != null) {
1985                                         // Check if function has any roles and which does not exist
1986                                         // in External Auth System. If exists delete in local
1987                                         addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
1988                                 }
1989                         }
1990
1991                         // Check if function does exits in External Auth System but exits in
1992                         // local then delete function and its dependencies
1993                         for (CentralV2RoleFunction roleFunc : appFunctions) {
1994                                 try {
1995                                         ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1996                                                         .get(roleFunc.getCode());
1997                                         if (null == getFunctionCodeContainsPipeKey) {
1998                                                 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1999                                                 if (null == getFunctionCodeKey) {
2000                                                         deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
2001                                                 }
2002                                         }
2003                                 } catch (Exception e) {
2004                                         logger.error(EELFLoggerDelegate.errorLogger,
2005                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
2006
2007                                 }
2008                         }
2009
2010                         logger.debug(EELFLoggerDelegate.debugLogger,
2011                                         "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
2012                 } catch (Exception e) {
2013                         logger.error(EELFLoggerDelegate.errorLogger,
2014                                         "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
2015
2016                 }
2017         }
2018
2019         @SuppressWarnings("unchecked")
2020         private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
2021                         List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
2022                         throws Exception {
2023                 if (!roleFunctionList.isEmpty()) {
2024                         final Map<String, String> appRoleFuncParams = new HashMap<>();
2025                         final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
2026                         final Map<String, String> currentRolesInExtSystem = new HashMap<>();
2027                         appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
2028                         appRoleFuncParams.put("appId", String.valueOf(app.getId()));
2029                         List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
2030                                         appRoleFuncParams, null);
2031                         for (LocalRole localRole : localRoleList) {
2032                                 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
2033                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
2034                         }
2035                         for (String addRole : roles) {
2036                                 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
2037                         }
2038                         for (String extAuthrole : roles) {
2039                                 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
2040                                 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
2041                                 if (isNameSpaceMatching) {
2042                                         if (!currentAppRoleFunctionsMap
2043                                                         .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
2044                                                 EPRole localAddFuntionRole = currentRolesInDB
2045                                                                 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
2046                                                 if (localAddFuntionRole == null) {
2047                                                         checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
2048                                                 } else {
2049                                                         EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2050                                                         addAppRoleFunc.setAppId(app.getId());
2051                                                         addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2052                                                         addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
2053                                                         dataAccessService.saveDomainObject(addAppRoleFunc, null);
2054                                                 }
2055                                         }
2056                                         // This block is to save global role function if exists
2057                                 } else {
2058                                         String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
2059                                         boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
2060                                         if (checkIfGlobalRoleExists) {
2061                                                 final Map<String, Long> params = new HashMap<>();
2062                                                 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
2063                                                 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
2064                                                 params.put("appId", app.getId());
2065                                                 params.put("roleId", role.getId());
2066                                                 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);                               
2067                                                 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
2068                                                 if (role != null && !checkIfRoleFunctionExists) {
2069                                                         addGlobalRoleFunctions.setAppId(app.getId());
2070                                                         addGlobalRoleFunctions.setRoleId(role.getId());
2071                                                         if (!app.getId().equals(role.getAppRoleId())) {
2072                                                                 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
2073                                                         } else {
2074                                                                 addGlobalRoleFunctions.setRoleAppId(null);
2075                                                         }
2076                                                         addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
2077                                                         dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
2078                                                 }
2079                                         }
2080                                 }
2081                         }
2082                         for (LocalRole localRoleDelete : localRoleList) {
2083                                 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
2084                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2085                                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2086                                                         APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
2087                                                                         + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
2088                                                         null);
2089                                 }
2090                         }
2091                 }
2092         }
2093
2094         private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2095                 logger.debug(EELFLoggerDelegate.debugLogger,
2096                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
2097                                 roleFunc.getCode());
2098                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2099                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2100                 logger.debug(EELFLoggerDelegate.debugLogger,
2101                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
2102                                 roleFunc.getCode());
2103
2104                 logger.debug(EELFLoggerDelegate.debugLogger,
2105                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
2106                                 roleFunc.getCode());
2107                 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2108                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2109                 logger.debug(EELFLoggerDelegate.debugLogger,
2110                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
2111                                 roleFunc.getCode());
2112         }
2113
2114         private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2115                         List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2116                 if (!currentRolesInDB.containsKey(
2117                                 roleList.substring(app.getNameSpace().length() + 1))) {
2118                         Role role = addRoleInDBIfDoesNotExists(app,
2119                                         roleList.substring(app.getNameSpace().length() + 1));
2120                         addIfRoleDescriptionNotExitsInExtSystem(role, app);
2121                         if (!roleFunctionList.isEmpty()) {
2122                                 try {
2123                                         if (!roleFunctionList.isEmpty()) {
2124                                                 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2125                                                 addAppRoleFunc.setAppId(app.getId());
2126                                                 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2127                                                 addAppRoleFunc.setRoleId(role.getId());
2128                                                 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2129                                         }
2130                                 } catch (Exception e) {
2131                                         logger.error(EELFLoggerDelegate.errorLogger,
2132                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
2133                                                         e);
2134                                 }
2135                         }
2136                 }
2137         }
2138
2139         @SuppressWarnings("unchecked")
2140         private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2141                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2142                 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2143                                 getFunctionCodeKey);
2144                 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2145                 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2146                 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2147                 List<CentralV2RoleFunction> roleFunctionList = null;
2148                 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2149                                 null);
2150                 if (roleFunctionList.isEmpty()) {
2151                         appSyncFuncsParams.put("functionCd", code);
2152                         roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2153                                         null);
2154                 }
2155                 return roleFunctionList;
2156         }
2157
2158         private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2159                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
2160                         ) {
2161                 String finalFunctionCodeVal = "";       
2162                 if (null == getFunctionCodeKey) {
2163                         finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2164                         CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2165                         // If function does not exist in local then add!
2166                         if (null == checkIfCodeStillExits) {
2167                                 logger.debug(EELFLoggerDelegate.debugLogger,
2168                                                 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2169                                 addFunctionInEcompDB(app, permsDetail, code);
2170                                 logger.debug(EELFLoggerDelegate.debugLogger,
2171                                                 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2172                         }
2173                 }
2174                 return finalFunctionCodeVal;
2175         }
2176
2177         @SuppressWarnings("unchecked")
2178         @Override
2179         public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
2180                 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2181                 List<EPRole> getCurrentRoleList = null;
2182                 final Map<String, Long> appParams = new HashMap<>();
2183                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2184                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2185                 } else {
2186                         appParams.put("appId", app.getId());
2187                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2188                 }
2189                 for (EPRole role : getCurrentRoleList) {
2190                         currentRolesInDB.put(role.getName()
2191                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2192                 }
2193                 return currentRolesInDB;
2194         }
2195
2196         private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
2197                         throws IOException{
2198                 ExternalAccessPermsDetail permDetails = null;
2199                 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2200                 for (int i = 0; i < extPerms.length(); i++) {
2201                         String description = null;
2202                         if (extPerms.getJSONObject(i).has("description")) {
2203                                 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2204                         } else {
2205                                 description = extPerms.getJSONObject(i).getString("instance");
2206                         }
2207                         if (extPerms.getJSONObject(i).has("roles")) {
2208                                 ObjectMapper rolesListMapper = new ObjectMapper();
2209                                 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2210                                 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2211                                                 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2212                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2213                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2214                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2215                                                                 + extPerms.getJSONObject(i).getString("action"),
2216                                                 extPerms.getJSONObject(i).getString("action"), list, description);
2217                                 permsDetailList.add(permDetails);
2218                         } else {
2219                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2220                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2221                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2222                                                                 + extPerms.getJSONObject(i).getString("action"),
2223                                                 extPerms.getJSONObject(i).getString("action"), description);
2224                                 permsDetailList.add(permDetails);
2225                         }
2226                 }
2227                 return permsDetailList;
2228         }
2229
2230         private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2231                 ResponseEntity<String> response = null;
2232                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2233                 HttpEntity<String> entity = new HttpEntity<>(headers);
2234                 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2235                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2236                 response = template
2237                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2238                                                 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2239
2240                 String res = response.getBody();
2241                 logger.debug(EELFLoggerDelegate.debugLogger,
2242                                 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2243                                 response.getBody());
2244                 JSONObject jsonObj = new JSONObject(res);
2245                 JSONArray extPerms = jsonObj.getJSONArray("perm");
2246                 for (int i = 0; i < extPerms.length(); i++) {
2247                         if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2248                                 extPerms.remove(i);
2249                                 i--;
2250                         }
2251                 }
2252                 return extPerms;
2253         }
2254         
2255         /**
2256          * 
2257          * Add function into local DB
2258          * 
2259          * @param app
2260          * @param permsDetail
2261          * @param code
2262          */
2263         private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2264                 try{
2265                 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2266                 addFunction.setAppId(app.getId());
2267                 addFunction.setCode(code);
2268                 addFunction.setName(permsDetail.getDescription());
2269                 dataAccessService.saveDomainObject(addFunction, null);
2270                 } catch(Exception e){
2271                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2272                 }
2273         }
2274
2275         /**
2276          * 
2277          * It updates description of a role in external auth system
2278          * 
2279          * @param role
2280          * @param app
2281          * @throws Exception
2282          */
2283         private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
2284                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2285                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2286                 try {
2287                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2288                         template.exchange(
2289                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2290                                         HttpMethod.PUT, entity, String.class);
2291                 } catch (HttpClientErrorException e) {
2292                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
2293                                         e);
2294                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2295                 } catch (Exception e) {
2296                         logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
2297                                         e);
2298                 }
2299         }
2300
2301         /**
2302          * 
2303          * While sync functions form external auth system if new role found we should add in local and return Role.class object
2304          * 
2305          * @param app
2306          * @param role
2307          * @return
2308          */
2309         @SuppressWarnings("unchecked")
2310         private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2311                 Role setNewRole = new Role();
2312                 try {
2313                         // functions can have new role created in External Auth System prevent
2314                         // duplication here
2315                         boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2316                         final Map<String, String> getRoleByNameParams = new HashMap<>();
2317                         List<EPRole> getRoleCreated = null;
2318                         getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2319                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2320                                 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2321                                 List<EPRole> roleCreated = dataAccessService
2322                                                 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2323                                 if (!isCreated) {
2324                                         EPRole epUpdateRole = roleCreated.get(0);
2325                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
2326                                         dataAccessService.saveDomainObject(epUpdateRole, null);
2327                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2328                                                         getRoleByNameParams, null);
2329                                 } else {
2330                                         getRoleCreated = roleCreated;
2331                                 }
2332                         } else {
2333                                 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2334                                                 null);
2335                         }
2336                         if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2337                                 EPRole roleObject = getRoleCreated.get(0);
2338                                 setNewRole.setId(roleObject.getId());
2339                                 setNewRole.setName(roleObject.getName());
2340                                 setNewRole.setActive(roleObject.getActive());
2341                                 setNewRole.setPriority(roleObject.getPriority());
2342                         }
2343                 } catch (Exception e) {
2344                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2345                 }
2346                 return setNewRole;
2347         }
2348
2349         @SuppressWarnings("unchecked")
2350         private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2351                 boolean isCreated = false;
2352                 final Map<String, String> roleParams = new HashMap<>();
2353                 roleParams.put(APP_ROLE_NAME_PARAM, role);
2354                 List<EPRole> roleCreated = null;
2355                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2356                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2357                                         null);
2358                 } else {
2359                         roleParams.put("appId", String.valueOf(app.getId()));
2360                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2361                                         null);
2362                 }
2363                 if (roleCreated == null || roleCreated.isEmpty()) {
2364                         roleParams.put("appId", String.valueOf(app.getId()));
2365                         EPRole epRoleNew = new EPRole();
2366                         epRoleNew.setActive(true);
2367                         epRoleNew.setName(role);
2368                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2369                                 epRoleNew.setAppId(null);
2370                         } else {
2371                                 epRoleNew.setAppId(app.getId());
2372                         }
2373                         dataAccessService.saveDomainObject(epRoleNew, null);
2374                         isCreated = false;
2375                 } else {
2376                         isCreated = true;
2377                 }
2378                 return isCreated;
2379         }
2380
2381         @Override
2382         @SuppressWarnings("unchecked")
2383         public Integer bulkUploadFunctions(String uebkey) throws Exception {
2384                 EPApp app = getApp(uebkey).get(0);
2385                 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2386                 CentralV2RoleFunction cenRoleFunc = null;
2387                 Integer functionsAdded = 0;
2388                 try {
2389                         for (RoleFunction roleFunc : roleFuncList) {
2390                                 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2391                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2392                                 functionsAdded++;
2393                         }
2394                 } catch(HttpClientErrorException e){
2395                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2396                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2397                 } catch (Exception e) {
2398                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2399                 }
2400                 return functionsAdded;
2401         }
2402
2403         @Override
2404         public Integer bulkUploadRoles(String uebkey) throws Exception {
2405                 List<EPApp> app = getApp(uebkey);
2406                 List<EPRole> roles = getAppRoles(app.get(0).getId());
2407                 List<CentralV2Role> cenRoleList = new ArrayList<>();
2408                 final Map<String, Long> params = new HashMap<>();
2409                 Integer rolesListAdded = 0;
2410                 try {
2411                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2412                         ObjectMapper mapper = new ObjectMapper();
2413                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2414                         String roleList = mapper.writeValueAsString(cenRoleList);
2415                         List<Role> roleObjectList = mapper.readValue(roleList,
2416                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2417                         for (Role role : roleObjectList) {
2418                                 addRoleInExternalSystem(role, app.get(0));
2419                                 rolesListAdded++;
2420                         }
2421                 } catch (Exception e) {
2422                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2423                         throw e;
2424                 }
2425                 return rolesListAdded;
2426         }
2427
2428         /**
2429          * It creating new role in external auth system while doing bulk upload
2430          * 
2431          * @param role
2432          * @param app
2433          * @throws Exception
2434          */
2435         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2436                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2437                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2438                 try {
2439                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2440                         template.exchange(
2441                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2442                                         HttpMethod.POST, entity, String.class);
2443                 } catch(HttpClientErrorException e){
2444                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
2445                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2446                 } catch (Exception e) {
2447                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2448                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2449                         } else {
2450                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2451                         }
2452                 }
2453         }
2454
2455         @Override
2456         @SuppressWarnings("unchecked")
2457         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2458                 EPApp app = getApp(uebkey).get(0);
2459                 List<EPRole> roles = getAppRoles(app.getId());
2460                 final Map<String, Long> params = new HashMap<>();
2461                 Integer roleFunctions = 0;
2462                 try {
2463                         for (EPRole role : roles) {
2464                                 params.put("roleId", role.getId());
2465                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2466                                                 params, null);
2467                                 if (!appRoleFunc.isEmpty()) {
2468                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2469                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2470                                                 roleFunctions++;
2471                                         }
2472                                 }
2473                         }
2474                 } catch(HttpClientErrorException e){
2475                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2476                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2477                 } catch (Exception e) {
2478                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2479                 }
2480                 return roleFunctions;
2481         }
2482         
2483         /**
2484          * Its adding a role function while doing bulk upload
2485          * 
2486          * @param addRoleFunc
2487          * @param role
2488          * @param app
2489          */
2490         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2491                 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2492                 ExternalAccessRolePerms extRolePerms = null;
2493                 ExternalAccessPerms extPerms = null;
2494                 ObjectMapper mapper = new ObjectMapper();
2495                 try {
2496                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2497
2498                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
2499                                         addRoleFunc.getFunctionName());
2500                         extRolePerms = new ExternalAccessRolePerms(extPerms,
2501                                         app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2502                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2503                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2504                         template.exchange(
2505                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2506                                         HttpMethod.POST, entity, String.class);
2507                 } catch (Exception e) {
2508                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2509                                 logger.error(EELFLoggerDelegate.errorLogger,
2510                                                 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
2511                         } else {
2512                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
2513                                                 e.getMessage());
2514                         }
2515                 }
2516         }
2517
2518         @Override
2519         public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
2520                 EPApp app = getApp(uebkey).get(0);
2521                 CentralV2RoleFunction cenRoleFunc = null;
2522                 for (RoleFunction roleFunction : roleFunctionsList) {
2523                         cenRoleFunc = new CentralV2RoleFunction(roleFunction.getCode(), roleFunction.getName());
2524                         addRoleFunctionInExternalSystem(cenRoleFunc, app);
2525                 }
2526         }
2527
2528         @Override
2529         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2530                 EPApp app = getApp(uebkey).get(0);
2531                 for (Role role : roleList) {
2532                         addRoleInExternalSystem(role, app);
2533                 }
2534         }
2535
2536         @SuppressWarnings("unchecked")
2537         @Override
2538         public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
2539                 EPApp app = getApp(uebkey).get(0);
2540                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2541                 for (Role role : roleList) {
2542                         try {
2543                                 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
2544                                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
2545                                 ObjectMapper roleFunctionsMapper = new ObjectMapper();
2546                                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
2547                                 while (itetaror.hasNext()) {
2548                                         Object nextValue = itetaror.next();
2549                                         RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
2550                                         roleFunctionListNew.add(roleFunction);
2551                                 }
2552                                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
2553                                                 .collect(Collectors.toList());
2554                                 for (RoleFunction roleFunction : listWithoutDuplicates) {
2555                                         String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
2556                                         ExternalAccessRolePerms extRolePerms = null;
2557                                         ExternalAccessPerms extPerms = null;
2558                                         ObjectMapper mapper = new ObjectMapper();
2559                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
2560                                                         "*");
2561                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
2562                                                         app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2563                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2564                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2565                                         template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2566                                                         + "role/perm", HttpMethod.PUT, entity, String.class);
2567                                 }
2568                         } catch (Exception e) {
2569                                 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2570                                         logger.error(EELFLoggerDelegate.errorLogger,
2571                                                         "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
2572                                 } else {
2573                                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
2574                                                         e);
2575                                 }
2576                         }
2577
2578                 }
2579         }
2580
2581         @Override
2582         @Transactional
2583         public void syncApplicationRolesWithEcompDB(EPApp app) {
2584                 try {
2585                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2586                         //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
2587                         syncRoleFunctionFromExternalAccessSystem(app);
2588                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");     
2589                         
2590                         ObjectMapper mapper = new ObjectMapper();
2591                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2592                         // Get Permissions from External Auth System
2593                         JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2594                         
2595                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2596                         List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
2597                                         mapper, extRole);
2598                         
2599                         List<EPRole> finalRoleList = new ArrayList<>();
2600                         for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2601                                 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2602                                 finalRoleList.add(ecompRole);
2603                         }
2604
2605                         List<EPRole> applicationRolesList;
2606                         applicationRolesList = getAppRoles(app.getId());
2607                         List<String> applicationRoleIdList = new ArrayList<>();
2608                         for (EPRole applicationRole : applicationRolesList) {
2609                                 applicationRoleIdList.add(applicationRole.getName());
2610                         }
2611
2612                         List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2613                         for (EPRole aafRole : finalRoleList) {
2614                                 if (!applicationRoleIdList.contains(aafRole.getName())) {
2615                                         roleListToBeAddInEcompDB.add(aafRole);
2616                                 }
2617                         }
2618
2619                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2620                         // Check if roles exits in external Access system and if not make inactive in DB
2621                         inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2622
2623                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
2624                         // It checks properties in the external auth system app role description and updates role in local
2625                         checkAndUpdateRoleInDB(app, finalRoleList);
2626
2627                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2628                         // Add new roles in DB and updates role description in External Auth System 
2629                         addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2630                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2631                 } catch (HttpClientErrorException e) {
2632                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2633                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2634                 } catch (Exception e) {
2635                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2636                 }
2637         }
2638
2639         /**
2640          * 
2641          * It adds new roles in DB and updates description in External Auth System
2642          * 
2643          * @param app
2644          * @param roleListToBeAddInEcompDB
2645          */
2646         @SuppressWarnings("unchecked")
2647         private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2648                 EPRole roleToBeAddedInEcompDB;
2649                 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2650                         try {
2651                                 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2652                                 if (app.getId() == 1) {
2653                                         roleToBeAddedInEcompDB.setAppRoleId(null);
2654                                 }
2655                                 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2656                                 List<EPRole> getRoleCreatedInSync = null;
2657                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2658                                         final Map<String, String> globalRoleParams = new HashMap<>();
2659                                         globalRoleParams.put("appId", String.valueOf(app.getId()));
2660                                         globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2661                                         getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2662                                         EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2663                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
2664                                         dataAccessService.saveDomainObject(epUpdateRole, null);
2665                                 }
2666                                 List<EPRole> roleList = new ArrayList<>();
2667                                 final Map<String, String> params = new HashMap<>();
2668
2669                                 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2670                                 boolean isPortalRole = false;
2671                                 if (app.getId() == 1) {
2672                                         isPortalRole = true;
2673                                         roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2674                                 } else {
2675                                         isPortalRole = false;
2676                                         params.put(APP_ID, app.getId().toString());
2677                                         roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
2678                                 }
2679                                 EPRole role = roleList.get(0);
2680                                 Role aaFrole = new Role();
2681                                 aaFrole.setId(role.getId());
2682                                 aaFrole.setActive(role.getActive());
2683                                 aaFrole.setPriority(role.getPriority());
2684                                 aaFrole.setName(role.getName());
2685                                 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2686                         } catch (Exception e) {
2687                                 logger.error(EELFLoggerDelegate.errorLogger,
2688                                                 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2689                         }
2690                 }
2691         }
2692
2693         /**
2694          * 
2695          * It checks description in External Auth System if found any changes updates in DB
2696          * 
2697          * @param app
2698          * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
2699          */
2700         @SuppressWarnings("unchecked")
2701         private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
2702                 for (EPRole roleItem : finalRoleList) {
2703                         final Map<String, String> roleParams = new HashMap<>();
2704                         List<EPRole> currentList = null;
2705                         roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
2706                         if (app.getId() == 1) {
2707                                 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2708                         } else {
2709                                 roleParams.put(APP_ID, app.getId().toString());
2710                                 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
2711                         }
2712
2713                         if (!currentList.isEmpty()) {
2714                                 try {
2715                                         Boolean aafRoleActive;
2716                                         Boolean localRoleActive;
2717                                         boolean result;
2718                                         aafRoleActive = Boolean.valueOf(roleItem.getActive());
2719                                         localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2720                                         result = aafRoleActive.equals(localRoleActive);
2721                                         EPRole updateRole = currentList.get(0);
2722
2723                                         if (!result) {
2724                                                 updateRole.setActive(roleItem.getActive());
2725                                                 dataAccessService.saveDomainObject(updateRole, null);
2726                                         }
2727                                         if (roleItem.getPriority() != null
2728                                                         && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2729                                                 updateRole.setPriority(roleItem.getPriority());
2730                                                 dataAccessService.saveDomainObject(updateRole, null);
2731                                         }
2732                                 } catch (Exception e) {
2733                                         logger.error(EELFLoggerDelegate.errorLogger,
2734                                                         "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2735                                 }
2736                         }
2737                 }
2738         }
2739         /**
2740          * 
2741          * It de-activates application roles in DB if not present in External Auth system  
2742          * 
2743          * @param app
2744          * @param finalRoleList contains list of current roles present in External Auth System
2745          * @param applicationRolesList contains list of current roles present in DB
2746          */
2747         @SuppressWarnings("unchecked")
2748         private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2749                         List<EPRole> applicationRolesList) {
2750                 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2751                 for (EPRole extrole : finalRoleList) {
2752                         checkRolesInactive.put(extrole.getName(), extrole);
2753                 }
2754                 for (EPRole role : applicationRolesList) {
2755                         try {
2756                                 final Map<String, String> extRoleParams = new HashMap<>();
2757                                 List<EPRole> roleList = null;
2758                                 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2759                                 if (!checkRolesInactive.containsKey(role.getName())) {
2760                                         if (app.getId() == 1) {
2761                                                 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2762                                         } else {
2763                                                 extRoleParams.put(APP_ID, app.getId().toString());
2764                                                 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
2765                                         }
2766                                         if(!roleList.isEmpty()) {
2767                                                 EPRole updateRoleInactive = roleList.get(0);
2768                                                 updateRoleInactive.setActive(false);
2769                                                 dataAccessService.saveDomainObject(updateRoleInactive, null);
2770                                         }
2771                                 }
2772                         } catch (Exception e) {
2773                                 logger.error(EELFLoggerDelegate.errorLogger,
2774                                                 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2775                         }
2776                 }
2777         }
2778         
2779         @Override
2780         @SuppressWarnings("unchecked")
2781         public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
2782                         ObjectMapper mapper, JSONArray extRole)
2783                         throws IOException {
2784                 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2785                 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
2786                 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); 
2787                 List<String> functionCodelist = new ArrayList<>();
2788                 for (int i = 0; i < extRole.length(); i++) {
2789                         ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2790                         EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2791                         JSONObject Role = (JSONObject) extRole.get(i);
2792                         if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2793                                 ApplicationRole.setActive("true");
2794                                 ApplicationRole.setAppId(IS_NULL_STRING);
2795                                 ApplicationRole.setPriority(IS_NULL_STRING);
2796                                 ApplicationRole.setAppRoleId(IS_NULL_STRING);
2797                                 String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
2798                                 ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
2799                         } else {
2800                                 String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2801                                 ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
2802                         }
2803
2804                         SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2805                         if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2806                                 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2807                                 for (int j = 0; j < extPerm.length(); j++) {
2808                                         JSONObject perms = extPerm.getJSONObject(j);
2809                                         boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"), app.getNameSpace());
2810                                         if (isNamespaceMatching) {
2811                                                 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2812                                                                 perms.getString("instance"), perms.getString("action"));
2813                                                 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2814                                                 functionCodelist.add(ePAppRoleFunction.getCode());
2815                                                 externalAccessPermsOfRole.add(externalAccessPerms);
2816                                         }
2817
2818                                 }
2819                         }
2820
2821                         if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
2822                                 externalRoleDetail.setActive(false);
2823                         } else {
2824                                 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
2825                         }
2826                         externalRoleDetail.setName(ApplicationRole.getName());
2827
2828                         if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
2829                                 externalRoleDetail.setAppId(null);
2830                         } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
2831                                 externalRoleDetail.setAppId(app.getId());
2832                         } else {
2833                                 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
2834                         }
2835
2836                         if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
2837                                 externalRoleDetail.setPriority(null);
2838                         } else {
2839                                 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
2840                         }
2841
2842                         if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
2843                                 externalRoleDetail.setAppRoleId(null);
2844                         }
2845
2846                         // get role functions from DB
2847                         final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2848                         if (!ApplicationRole.getId().equals(IS_NULL_STRING)) {
2849                                 final Map<String, Long> appRoleFuncsParams = new  HashMap<>();
2850                                 appRoleFuncsParams.put("appId", app.getId());
2851                                 appRoleFuncsParams.put("roleId", Long.valueOf(ApplicationRole.getId()));
2852                                 List<EPAppRoleFunction> appRoleFunctions = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2853                                 if (!appRoleFunctions.isEmpty()) {
2854                                         for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2855                                                 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2856                                         }
2857                                 }
2858                         }
2859
2860                         if (!externalAccessPermsOfRole.isEmpty()) {
2861                                 // Adding functions to role
2862                                 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2863                                         EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2864                                         if (checkRoleFunctionExits == null) {
2865                                                 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2866                                                                 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2867                                                                 + externalpermission.getAction();
2868                                                 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2869                                                 if (checkRoleFunctionPipeExits == null) {
2870                                                         try {
2871                                                                 final Map<String, String> appFuncsParams = new  HashMap<>();
2872                                                                 appFuncsParams.put("appId", String.valueOf(app.getId()));
2873                                                                 appFuncsParams.put("functionCd", externalpermission.getInstance());
2874                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
2875                                                                                 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2876                                                                                 externalpermission.getInstance());
2877                                                                 List<CentralV2RoleFunction> roleFunction = null;
2878                                                                 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
2879                                                                 if (roleFunction.isEmpty()) {
2880                                                                         appFuncsParams.put("functionCd", funcCode);
2881                                                                         roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
2882                                                                 }
2883                                                                 if (!roleFunction.isEmpty()) {
2884                                                                         EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2885                                                                         apRoleFunction.setAppId(app.getId());
2886                                                                         apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
2887                                                                         apRoleFunction.setCode(roleFunction.get(0).getCode());
2888                                                                         dataAccessService.saveDomainObject(apRoleFunction, null);
2889                                                                 }
2890                                                         } catch (Exception e) {
2891                                                                 logger.error(EELFLoggerDelegate.errorLogger,
2892                                                                                 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2893                                                         }
2894                                                 }
2895                                         }
2896                                 }
2897                         }
2898                         externalRoleDetailsList.add(externalRoleDetail);
2899                 }
2900                 return externalRoleDetailsList;
2901         }
2902
2903         @Override
2904         public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2905                 ResponseEntity<String> response = null;
2906                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2907                 HttpEntity<String> entity = new HttpEntity<>(headers);
2908                 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2909                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2910                 response = template
2911                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2912                                                 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2913                 String res = response.getBody();
2914                 logger.debug(EELFLoggerDelegate.debugLogger,
2915                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2916                                 res);
2917                 JSONObject jsonObj = new JSONObject(res);
2918                 JSONArray extRole = jsonObj.getJSONArray("role");
2919                 for (int i = 0; i < extRole.length(); i++) {
2920                         if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2921                                         || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2922                                         || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2923                                                         && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
2924                                 extRole.remove(i);
2925                                 i--;
2926                         }                       
2927                 }
2928                 return extRole;
2929         }
2930         
2931         @Override
2932         public JSONArray getAllUsersByRole(String roleName) throws Exception{
2933                 ResponseEntity<String> response = null;
2934                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2935                 HttpEntity<String> entity = new HttpEntity<>(headers);
2936                 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
2937                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2938                 response = template
2939                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2940                                                 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
2941                 String res = response.getBody();
2942                 logger.debug(EELFLoggerDelegate.debugLogger,
2943                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2944                                 res);
2945                 JSONObject jsonObj = new JSONObject(res);
2946                 JSONArray extRole = jsonObj.getJSONArray("userRole");
2947                 
2948                 return extRole;
2949         }
2950
2951         /**
2952          * 
2953          * It converts from ExternalRoleDetails.class object to EPRole.class object
2954          * 
2955          * @param externalRoleDetails
2956          * @return EPRole object
2957          */
2958         private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2959                 EPRole role = new EPRole();
2960                 role.setActive(externalRoleDetails.isActive());
2961                 role.setAppId(externalRoleDetails.getAppId());
2962                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2963                 role.setName(externalRoleDetails.getName());
2964                 role.setPriority(externalRoleDetails.getPriority());
2965                 return role;
2966         }
2967
2968         @SuppressWarnings("unchecked")
2969         @Override
2970         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2971                 EPApp app = getApp(uebkey).get(0);
2972                 final Map<String, String> params = new HashMap<>();
2973                 params.put("uebKey", app.getUebKey());
2974                 List<BulkUploadUserRoles> userRolesList = null;
2975                 Integer userRolesAdded = 0;
2976                 if (app.getCentralAuth()) {
2977                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2978                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2979                                 if(!userRolesUpload.getOrgUserId().equals("su1234")){
2980                                         addUserRoleInExternalSystem(userRolesUpload);
2981                                         userRolesAdded++;
2982                                 }
2983                         }
2984                 }
2985                 return userRolesAdded;
2986         }
2987
2988         /**
2989          * Its adding a user role in external auth system while doing bulk upload 
2990          * 
2991          * @param userRolesUpload
2992          */
2993         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2994                 try {
2995                         String name = "";
2996                         ObjectMapper mapper = new ObjectMapper();
2997                         if (EPCommonSystemProperties
2998                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2999                                 name = userRolesUpload.getOrgUserId()
3000                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3001                         }
3002                         ExternalAccessUser extUser = new ExternalAccessUser(name,
3003                                         userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3004                         String userRole = mapper.writeValueAsString(extUser);
3005                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3006                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
3007                         template.exchange(
3008                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
3009                                         HttpMethod.POST, entity, String.class);
3010                 } catch(HttpClientErrorException e){
3011                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3012                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3013                 } catch (Exception e) {
3014                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3015                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3016                         } else {
3017                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3018                         }
3019                 }
3020         }
3021
3022         @Override
3023         public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
3024                 try {
3025                         String sql = ""; 
3026                         Query query = null;
3027                         
3028                         //It should delete only when it portal's roleId
3029                         if(appId.equals(PortalConstants.PORTAL_APP_ID)){
3030                         // Delete from fn_role_function
3031                         sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3032                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3033                         query = localSession.createSQLQuery(sql);
3034                         query.executeUpdate();
3035                         
3036                         // Delete from fn_role_composite
3037                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3038                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3039                         query = localSession.createSQLQuery(sql);
3040                         query.executeUpdate();
3041                         }
3042                         
3043                         // Delete from ep_app_role_function
3044                         sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3045                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3046                         query = localSession.createSQLQuery(sql);
3047                         query.executeUpdate();
3048
3049                         // Delete from ep_role_notification
3050                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3051                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3052                         query = localSession.createSQLQuery(sql);
3053                         query.executeUpdate();
3054                         
3055                         // Delete from fn_user_pseudo_role
3056                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3057                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3058                         query = localSession.createSQLQuery(sql);
3059                         query.executeUpdate();
3060
3061                         // Delete form EP_WIDGET_CATALOG_ROLE
3062                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3063                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3064                         query = localSession.createSQLQuery(sql);
3065                         query.executeUpdate();
3066
3067                         // Delete form EP_WIDGET_CATALOG_ROLE
3068                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3069                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3070                         query = localSession.createSQLQuery(sql);
3071                         query.executeUpdate();
3072
3073                         if(!isPortalRequest) {
3074                                 // Delete form fn_menu_functional_roles
3075                                 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3076                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3077                                 query = localSession.createSQLQuery(sql);
3078                                 query.executeUpdate();  
3079                         }
3080                 } catch (Exception e) {
3081                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3082                         throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3083                 }
3084
3085         }
3086         
3087         @SuppressWarnings("unchecked")
3088         @Override
3089         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3090                 List<String> appMenuFunctionsList = null;
3091                 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3092                 try {
3093                         EPApp app = getApp(uebkey).get(0);
3094                         final Map<String, Long> appParams = new HashMap<>();
3095                         appParams.put(APP_ID, app.getId());
3096                         appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3097                         for(String appMenuFunction : appMenuFunctionsList) {
3098                                 if(appMenuFunction.contains(FUNCTION_PIPE)) {
3099                                         appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3100                                 } else {
3101                                         appMenuFunctionsFinalList.add(appMenuFunction);
3102                                 }
3103                         }
3104                 } catch (Exception e) {
3105                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3106                         return appMenuFunctionsFinalList;
3107                 }
3108                 return appMenuFunctionsFinalList;
3109         }
3110
3111         @SuppressWarnings({ "unchecked"})
3112         @Override
3113         public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3114                 List<String> usersList = new ArrayList<>();
3115         List<EcompUser> usersfinalList = new ArrayList<>();
3116         try {
3117                EPApp app = getApp(uebkey).get(0);
3118                final Map<String, Long> appParams = new HashMap<>();
3119                appParams.put("appId", app.getId());
3120                List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3121                             .executeNamedQuery("ApplicationUserRoles", appParams, null);
3122                for (EcompUserRoles ecompUserRole : userList) {
3123                      boolean found = false;
3124                      Set<EcompRole> roles = null;
3125                      for (EcompUser user : usersfinalList) {
3126                             if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3127                                    EcompRole ecompRole = new EcompRole();
3128                                    ecompRole.setId(ecompUserRole.getRoleId());
3129                                    ecompRole.setName(ecompUserRole.getRoleName());
3130                                    roles = user.getRoles();
3131                                    EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny()
3132                                                  .orElse(null);
3133                                    SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3134                                    if(role != null)
3135                                    {
3136                                           roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3137                                    }
3138                                           
3139                              String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3140                             functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3141                             EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3142                             epRoleFunction.setName(ecompUserRole.getFunctionName());
3143                             epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3144                             epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3145                             epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3146                             roleFunctionSet.add(epRoleFunction);
3147                         ecompRole.setRoleFunctions(roleFunctionSet);
3148                                    roles.add(ecompRole);
3149                                    user.setRoles(roles);
3150                                    found = true;
3151                                    break;
3152                             }
3153                      }
3154
3155                      if (!found) {
3156                             EcompUser epUser = new EcompUser();
3157                             epUser.setOrgId(ecompUserRole.getOrgId());
3158                             epUser.setManagerId(ecompUserRole.getManagerId());
3159                             epUser.setFirstName(ecompUserRole.getFirstName());
3160                             epUser.setLastName(ecompUserRole.getLastName());
3161                             epUser.setPhone(ecompUserRole.getPhone());
3162                             epUser.setEmail(ecompUserRole.getEmail());
3163                             epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3164                             epUser.setOrgCode(ecompUserRole.getOrgCode());
3165                             epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3166                             epUser.setJobTitle(ecompUserRole.getJobTitle());
3167                             epUser.setLoginId(ecompUserRole.getLoginId());
3168                             epUser.setActive(true);
3169                             roles = new HashSet<>();
3170                             EcompRole ecompRole = new EcompRole();
3171                             ecompRole.setId(ecompUserRole.getRoleId());
3172                             ecompRole.setName(ecompUserRole.getRoleName());
3173               SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3174               
3175                             String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3176               functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3177               EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3178               epRoleFunction.setName(ecompUserRole.getFunctionName());
3179               epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3180               epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3181               epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3182               roleFunctionSet.add(epRoleFunction);
3183               ecompRole.setRoleFunctions(roleFunctionSet);
3184                             roles.add(ecompRole);
3185                             epUser.setRoles(roles);
3186                             usersfinalList.add(epUser);
3187                      }
3188                }
3189                ObjectMapper mapper = new ObjectMapper();
3190
3191                for (EcompUser u1 : usersfinalList) {
3192                      String str = mapper.writeValueAsString(u1);
3193                      usersList.add(str);
3194                }
3195         } catch (Exception e) {
3196                logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3197                throw e;
3198         }
3199         return usersfinalList;
3200
3201         }
3202         
3203
3204         @Override
3205         public Role ConvertCentralRoleToRole(String result) {
3206                 ObjectMapper mapper = new ObjectMapper();
3207                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3208                 Role newRole = new Role();
3209                 try {
3210                         newRole = mapper.readValue(result, Role.class);
3211                 } catch (IOException e) {
3212                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3213                 }
3214                 if (newRole.getRoleFunctions() != null) {
3215                         @SuppressWarnings("unchecked")
3216                         Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3217                         Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3218                         Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3219                         while (itetaror.hasNext()) {
3220                                 Object nextValue = itetaror.next();
3221                                 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3222                                 roleFunctionListNew.add(roleFun);
3223                         }
3224                         newRole.setRoleFunctions(roleFunctionListNew);
3225                 }
3226                 return newRole;
3227         }
3228         
3229         @Override
3230         @SuppressWarnings("unchecked")
3231         public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3232                 Map<String, String> params = new HashMap<>();
3233                 params.put("userId", userId);
3234                 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3235                 try{
3236                         centralizedAppsList =  dataAccessService
3237                                         .executeNamedQuery("getCentralizedAppsOfUser", params, null);
3238                 }catch (Exception e) {
3239                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3240                 }
3241                 return centralizedAppsList;
3242         }
3243
3244         @SuppressWarnings("unchecked")
3245         public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3246                 Map<String, Long> params = new HashMap<>();
3247                 params.put("appId", appId);
3248                 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3249                 try {
3250                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3251                                         null);
3252                 } catch (Exception e) {
3253                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3254                 }
3255                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3256                 if (globalRoles.size() > 0)
3257                         rolesfinalList = finalListOfCentralRoles(globalRoles);
3258                 return rolesfinalList;
3259         }
3260
3261         @SuppressWarnings("unchecked")
3262         private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3263                 CentralV2Role finalGlobalrole = null;
3264                 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3265                 Map<String, Long> params = new HashMap<>();
3266                 params.put("roleId", roleId);
3267                 params.put("requestedAppId", requestedAppId);
3268                 try {
3269                         roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3270                                         params, null);
3271                 } catch (Exception e) {
3272                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3273                 }
3274                 if (roleWithApplicationRoleFucntions.size() > 0) {
3275                         List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3276                         finalGlobalrole = rolesfinalList.get(0);
3277                 } else {
3278                         List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3279                         finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3280                 }
3281                 return finalGlobalrole;
3282         }
3283
3284         private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3285                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3286                 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3287                         boolean found = false;
3288                         for (CentralV2Role cenRole : rolesfinalList) {
3289                                 if (role.getRoleId().equals(cenRole.getId())) {
3290                                         SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3291                                         CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3292                                         roleFunctions.add(cenRoleFun);
3293                                         cenRole.setRoleFunctions(roleFunctions);
3294                                         found = true;
3295                                         break;
3296                                 }
3297                         }
3298                         if (!found) {
3299                                 CentralV2Role cenrole = new CentralV2Role();
3300                                 cenrole.setName(role.getRoleName());
3301                                 cenrole.setId(role.getRoleId());
3302                                 cenrole.setActive(role.isActive());
3303                                 cenrole.setPriority(role.getPriority());
3304                                 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3305                                 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3306                                 roleFunctions.add(cenRoleFun);
3307                                 cenrole.setRoleFunctions(roleFunctions);
3308                                 rolesfinalList.add(cenrole);
3309                         }
3310                 }
3311                 return rolesfinalList;
3312         }
3313
3314         private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3315                 String instance;
3316                 String type;
3317                 String action;
3318                 CentralV2RoleFunction cenRoleFun;
3319                 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
3320                         instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3321                         type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3322                         action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3323                         cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3324                 } else{
3325                         type = getFunctionCodeType(role.getFunctionCd());
3326                         action = getFunctionCodeAction(role.getFunctionCd());
3327                         cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
3328                 }
3329                 return cenRoleFun;
3330         }
3331
3332         @SuppressWarnings("unchecked")
3333         @Override
3334         public List<EPRole> getGlobalRolesOfPortal() {
3335                 List<EPRole> globalRoles = new ArrayList<>();
3336                 try {
3337                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3338                 } catch (Exception e) {
3339                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3340                 }
3341                 return globalRoles;
3342         }
3343
3344         private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3345          return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3346                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3347                                 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3348                 
3349         }
3350         
3351         @Override
3352         public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
3353                 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3354                 for(CentralV2RoleFunction cenRoleFunc : answer){
3355                         CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3356                         setRoleFunc.setCode(cenRoleFunc.getCode());
3357                         setRoleFunc.setName(cenRoleFunc.getName());
3358                         addRoleFuncList.add(setRoleFunc);
3359                 }               
3360                 return addRoleFuncList;
3361         }
3362
3363         @Override
3364         public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3365                 CentralUser sendUserRoles = null;
3366
3367                 try {
3368                         CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3369                         sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3370                 } catch (Exception e) {
3371                         logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3372                         throw e;
3373                 }
3374                 return sendUserRoles;
3375         }
3376
3377         /**
3378          * 
3379          * It returns V2 CentralUser object if user has any roles and permissions
3380          * 
3381          * @param loginId
3382          * @param uebkey
3383          * @return CentralUser object
3384          * @throws Exception
3385          */
3386         private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3387                 EPApp app;
3388                 List<EPUser> epUserList;
3389                 List<EPApp> appList = getApp(uebkey);
3390                 app = appList.get(0);
3391                 epUserList = getUser(loginId);
3392                 EPUser user = epUserList.get(0);
3393                 Set<EPUserApp> userAppSet = user.getEPUserApps();
3394                 return createEPUser(user, userAppSet, app);
3395         }
3396
3397         /**
3398          * It converts V2 CentralUser object to old version CentralUser object
3399          * 
3400          * @param cenV2User
3401          * @return EPUser object
3402          */
3403         private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3404                         Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3405                         Set<CentralUserApp> userApps = new TreeSet<>();
3406                         for(CentralV2UserApp userApp : userV2Apps){                             
3407                                 CentralApp app  = userApp.getApp();
3408                                 CentralUserApp cua = new CentralUserApp();
3409                                 cua.setUserId(null);
3410                                 cua.setApp(app);
3411                                 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3412                                 for(CentralV2RoleFunction  cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){                                      
3413                                         CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());                                                            
3414                                         cenRoleFunction.add(cenRoleFunc);
3415                                 }
3416                                 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().isActive(), userApp.getRole().getPriority(),
3417                                                 cenRoleFunction);
3418                                 cua.setRole(role);
3419                                 userApps.add(cua);
3420                         }
3421                         return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(), 
3422                                         cenV2User.getCreatedId(),cenV2User.getModifiedId(), 
3423                                         cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(), 
3424                                         cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), 
3425                                         cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
3426                                         cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(), 
3427                                         cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(), 
3428                                         cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(), 
3429                                         cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(), 
3430                                         cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(), 
3431                                         cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(), 
3432                                         cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
3433                                         cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(), 
3434                                         cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
3435                                         cenV2User.isOnline(),cenV2User.getChatId(), 
3436                                         userApps);
3437         }
3438
3439         @Override
3440         public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3441                 List<CentralRole> cenRoleList = new ArrayList<>();
3442                         for(CentralV2Role v2CenRole : v2CenRoleList){
3443                                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3444                                 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
3445                                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3446                                         cenRoleFuncList.add(roleFunc);
3447                                 }
3448                                 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), cenRoleFuncList);
3449                                 cenRoleList.add(role);
3450                         }               
3451                 return cenRoleList;
3452         }
3453         
3454         @Override
3455         public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3456                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3457                 HttpEntity<String> entity = new HttpEntity<>(headers);
3458                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3459                 ResponseEntity<String> response = null;
3460                 try {
3461                         response = template
3462                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3463                                                         + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3464                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3465                                         response.getStatusCode().value());
3466                 } catch (HttpClientErrorException e) {
3467                         logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3468                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3469                         if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3470                                 throw new InvalidApplicationException("Invalid NameSpace");
3471                         else
3472                                 throw e;
3473                 }
3474                 return response;
3475         }
3476         
3477         @Override
3478         public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3479                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3480                 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3481                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3482                         cenRoleFuncList.add(roleFunc);
3483                 }
3484                 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(),
3485                                 cenRoleFuncList);
3486         }
3487
3488         @SuppressWarnings("unchecked")
3489         @Override
3490         public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3491                 EPApp app = getApp(uebkey).get(0);
3492                 final Map<String, String> params = new HashMap<>();
3493                 params.put("uebKey", app.getUebKey());
3494                 params.put("roleId", String.valueOf(roleId));
3495                 List<BulkUploadUserRoles> userRolesList = null;
3496                 Integer userRolesAdded = 0;
3497                 if (app.getCentralAuth()) {
3498                         userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3499                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3500                                 userRolesUpload.setRoleName(modifiedRoleName);
3501                                 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3502                                         addUserRoleInExternalSystem(userRolesUpload);
3503                                         userRolesAdded++;
3504                                 }
3505                         }
3506                 }
3507                 return userRolesAdded;
3508         }       
3509         
3510         @Override
3511         public String encodeFunctionCode(String funCode){
3512                 String encodedString = funCode;
3513                 List<Pattern> encodingList = new ArrayList<>();
3514                 encodingList.add(Pattern.compile("/"));
3515                 encodingList.add(Pattern.compile("-"));
3516                 for (Pattern xssInputPattern : encodingList) {
3517                         encodedString = xssInputPattern.matcher(encodedString)
3518                                         .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
3519                 }               
3520                 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
3521                 return encodedString;
3522         }
3523 }