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