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