Merge "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 = getFunctionCodeType(roleFunc.getCode());
517                         action = getFunctionCodeAction(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 = getFunctionCodeType(addFunction.getCode());
667                                         action = getFunctionCodeAction(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 = getFunctionCodeType(roleFunc.getCode());
724                                 action = getFunctionCodeAction(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 = getFunctionCodeType(roleFuncItem.getCode());
1195                         String action = getFunctionCodeAction(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         @Override
1206         public String getFunctionCodeAction(String roleFuncItem) {
1207                 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
1208                                 : EcompPortalUtils.getFunctionAction(roleFuncItem);
1209         }
1210
1211         @Override
1212         public String getFunctionCodeType(String roleFuncItem) {
1213                 String type = null;
1214                 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1215                                 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1216                         type = "menu";
1217                 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
1218                                 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1219                                 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1220                         type = "url";
1221                 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1222                                 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1223                         type = EcompPortalUtils.getFunctionType(roleFuncItem);
1224                 }
1225                 return type;
1226         }
1227
1228         /**
1229          * 
1230          * It check whether function code has no pipes and no url string in it
1231          * 
1232          * @param roleFuncItem
1233          * @return true or false
1234          */
1235         private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1236                 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1237         }
1238         
1239         /**
1240          * 
1241          * It check whether function code has pipes and url string in it  
1242          * 
1243          * @param roleFuncItem
1244          * @return true or false
1245          */
1246         private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1247                 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1248         }
1249
1250         /**
1251          * 
1252          * It check whether function code has no pipes and has url string in it 
1253          * 
1254          * @param roleFuncItem
1255          * @return true or false
1256          */
1257         private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1258                 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1259         }
1260
1261         /**
1262          * It returns user detail information which is deep copy of EPUser.class object
1263          * 
1264          * @param userInfo
1265          * @param userAppSet
1266          * @param app
1267          * @return
1268          * @throws Exception
1269          */
1270         @SuppressWarnings("unchecked")
1271         private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1272
1273                 final Map<String, Long> params = new HashMap<>();
1274                 CentralV2User userAppList = new CentralV2User();
1275                 CentralV2User user1 = null;
1276                 final Map<String, Long> params1 = new HashMap<>();
1277                 List<EPRole> globalRoleList = new ArrayList<>();
1278
1279                 try {
1280                         if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1281                                 params1.put("userId", userInfo.getId());
1282                                 params1.put("appId", app.getId());
1283                                 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1284                         }
1285                         userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1286                         for (EPUserApp userApp : userAppSet) {
1287                                 if (userApp.getRole().getActive()) {
1288                                         EPApp epApp = userApp.getApp();
1289                                         String globalRole = userApp.getRole().getName().toLowerCase();
1290                                         if (((epApp.getId().equals(app.getId()))
1291                                                         && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1292                                                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1293                                                                         && (globalRole.toLowerCase().startsWith("global_")))) {
1294                                                 CentralV2UserApp cua = new CentralV2UserApp();
1295                                                 cua.setUserId(null);
1296                                                 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1297                                                                 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1298                                                                 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1299                                                                 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1300                                                                 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1301                                                                 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1302                                                                 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1303                                                                 epApp.getUebTopicName());
1304                                                 cua.setApp(cenApp);
1305                                                 Long appId = null;
1306                                                 if (globalRole.toLowerCase().startsWith("global_")
1307                                                                 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1308                                                                 && !epApp.getId().equals(app.getId())) {
1309                                                         appId = app.getId();
1310                                                         EPRole result = null;
1311                                                         if (globalRoleList.size() > 0)
1312                                                                 result = globalRoleList.stream()
1313                                                                                 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1314                                                                                 .orElse(null);
1315                                                         if (result == null)
1316                                                                 continue;
1317                                                 } else {
1318                                                         appId = userApp.getApp().getId();
1319                                                 }
1320                                                 params.put("roleId", userApp.getRole().getId());
1321                                                 params.put(APP_ID, appId);
1322                                                 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1323                                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
1324                                                 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1325                                                 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1326                                                         String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1327                                                         CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1328                                                                         functionCode, roleFunc.getName(), null, null);
1329                                                         roleFunctionSet.add(cenRoleFunc);
1330                                                 }
1331                                                 Long userRoleId = null;
1332                                                 if (globalRole.toLowerCase().startsWith("global_")
1333                                                                 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1334                                                         userRoleId = userApp.getRole().getId();
1335                                                 } else {
1336                                                         userRoleId = userApp.getRole().getAppRoleId();
1337                                                 }
1338                                                 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1339                                                                 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1340                                                                 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1341                                                                 userApp.getRole().getName(), userApp.getRole().getActive(),
1342                                                                 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1343                                                 cua.setRole(cenRole);
1344
1345                                                 userAppList.getUserApps().add(cua);
1346                                         }
1347                                 }
1348                         }
1349
1350                         user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1351                                         userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1352                                         userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1353                                         userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1354                                         userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1355                                         userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1356                                         userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1357                                         userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1358                                         userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1359                                         userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1360                                         userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1361                                         userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1362                                         userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1363                                         userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1364                                         userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1365                 } catch (Exception e) {
1366                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1367                         throw e;
1368                 }
1369                 return user1;
1370         }
1371
1372         @Override
1373         public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1374                 final Map<String, Long> params = new HashMap<>();
1375                 List<CentralV2Role> roleList = new ArrayList<>();
1376                 CentralV2Role cenRole = new CentralV2Role();
1377                 List<EPRole> roleInfo = null;
1378                 List<EPApp> app = null;
1379                 try {
1380                         app = getApp(uebkey);
1381                         if (app.isEmpty()) {
1382                                 throw new InactiveApplicationException("Application not found");
1383                         }
1384                         if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1385                                 List<EPRole> globalRoleList = new ArrayList<>();
1386                                 globalRoleList = getGlobalRolesOfPortal();
1387                                 if (globalRoleList.size() > 0) {
1388                                         EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1389                                                         .orElse(null);
1390                                         if (result != null)
1391                                                 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1392                                 }
1393                         }
1394                         if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1395                                 roleInfo = getPortalAppRoleInfo(roleId);
1396                         } else {
1397                                 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1398                         }
1399                         roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1400                         if (roleList.isEmpty()) {
1401                                 return cenRole;
1402                         }
1403
1404                 } catch (Exception e) {
1405                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1406                         throw e;
1407
1408                 }
1409                 return roleList.get(0);
1410         }
1411
1412         @SuppressWarnings("unchecked")
1413         private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1414                 List<EPRole> roleInfo;
1415                 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1416                 getPartnerAppRoleParams.put("appRoleId", roleId);
1417                 getPartnerAppRoleParams.put("appId", app.getId());                              
1418                 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1419                 if(roleInfo.isEmpty()) {
1420                         getPartnerAppRoleParams.put("appRoleId", roleId);
1421                         roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1422                 }
1423                 return roleInfo;
1424         }
1425
1426         @SuppressWarnings("unchecked")
1427         private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1428                 List<EPRole> roleInfo;
1429                 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1430                 getPortalAppRoleParams.put("roleId", roleId);
1431                 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1432                 return roleInfo;
1433         }
1434         
1435         /**
1436          * 
1437          * It returns list of app roles along with role functions and which went through deep copy
1438          * 
1439          * @param app
1440          * @param roleInfo
1441          * @param roleList
1442          * @param params
1443          * @return
1444          * @throws DecoderException 
1445          */
1446         @SuppressWarnings("unchecked")
1447         private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1448                         List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1449                 for (EPRole role : roleInfo) {
1450                         params.put("roleId", role.getId());
1451                         params.put(APP_ID, app.get(0).getId());
1452                         List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1453                                         params, null);
1454                         SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1455                         for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1456                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1457                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1458                                 String type = getFunctionCodeType(roleFunc.getCode());
1459                                 String action = getFunctionCodeAction(roleFunc.getCode());
1460                                 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1461                                                 roleFunc.getName(), null, type, action, null);
1462                                 roleFunctionSet.add(cenRoleFunc);
1463                         }
1464                         SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1465                         SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1466                         CentralV2Role cenRole = null;
1467                         if (role.getAppRoleId() == null) {
1468                                 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1469                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1470                                                 roleFunctionSet, childRoles, parentRoles);
1471                         } else {
1472                                 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1473                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1474                                                 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1475                         }
1476                         roleList.add(cenRole);
1477                 }
1478                 return roleList;
1479         }
1480
1481         @SuppressWarnings("unchecked")
1482         @Override
1483         public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1484                 String code = EcompPortalUtils.getFunctionCode(functionCode);
1485                 String encodedCode = encodeFunctionCode(code);
1486                 CentralV2RoleFunction roleFunc = null;
1487                 EPApp app = getApp(uebkey).get(0);
1488                 List<CentralV2RoleFunction> getRoleFuncList = null;
1489                 final Map<String, String> params = new HashMap<>();
1490                 try {
1491                         params.put(FUNCTION_CODE_PARAMS, functionCode);
1492                         params.put(APP_ID, String.valueOf(app.getId()));
1493                         getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1494                         if (getRoleFuncList.isEmpty()) {
1495                                 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1496                                 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1497                                 if (getRoleFuncList.isEmpty()) {
1498                                         return roleFunc;
1499                                 }
1500                         }
1501                         if (getRoleFuncList.size() > 1) {
1502                                 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1503                                 if (cenV2RoleFunction == null)
1504                                         return roleFunc;
1505                                 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1506                         } else {
1507                                 roleFunc = getRoleFuncList.get(0);
1508                         }
1509                 } catch (Exception e) {
1510                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1511                         throw e;
1512                 }
1513                 return roleFunc;
1514         }
1515
1516         private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1517                 CentralV2RoleFunction roleFunc;
1518                 String functionCodeFormat = getRoleFuncList.getCode();
1519                 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1520                         String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1521                         String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1522                         String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1523                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1524                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
1525                                         getRoleFuncList.getEditUrl());
1526                 } else {
1527                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
1528                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(),
1529                                         getRoleFuncList.getEditUrl());
1530                 }
1531                 return roleFunc;
1532         }
1533
1534         @Override
1535         public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1536                 boolean saveOrUpdateFunction = false;
1537                 try {
1538                         domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
1539                         final Map<String, String> functionParams = new HashMap<>();
1540                         functionParams.put("appId", String.valueOf(app.getId()));
1541                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1542                                 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);                        
1543                         }
1544                         if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
1545                                 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
1546                                         FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
1547                         }
1548                         domainCentralRoleFunction.setAppId(app.getId());
1549                         dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1550                         saveOrUpdateFunction = true;
1551                 } catch (Exception e) {
1552                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1553                         throw e;
1554                 }
1555                 return saveOrUpdateFunction;
1556         }
1557         
1558         /**
1559          * It creates application permission in external auth system
1560          * 
1561          * @param domainCentralRoleFunction
1562          * @param app
1563          * @throws Exception
1564          */
1565         private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1566                         throws Exception {
1567                 ObjectMapper mapper = new ObjectMapper();
1568                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1569                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); 
1570                 String type = "";
1571                 String instance = "";
1572                 String action = "";
1573                 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1574                         type =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType(); 
1575                         instance =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ?  EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
1576                         action =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
1577                 } else{
1578                         type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1579                         instance = domainCentralRoleFunction.getCode();
1580                         action = "*"; 
1581                 }               
1582                 // get Permissions from External Auth System
1583                 JSONArray extPermsList = getExtAuthPermissions(app);
1584                 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1585                 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
1586                 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1587                 if (!checkIfFunctionsExits) {
1588                         try {
1589                                 extPerms.setAction(action);
1590                                 extPerms.setInstance(instance);
1591                                 extPerms.setType(app.getNameSpace() + "." + type);
1592                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1593                                 String addFunction = mapper.writeValueAsString(extPerms);
1594                                 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1595                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1596                                 ResponseEntity<String> addPermResponse= template.exchange(
1597                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1598                                                 HttpMethod.POST, entity, String.class);
1599                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
1600                         } catch(HttpClientErrorException e){
1601                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1602                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1603                                 throw e;
1604                         }catch (Exception e) {
1605                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1606                                                 e);
1607                                 throw e;
1608                         }
1609                 } else {
1610                         try {
1611                                 extPerms.setAction(action);
1612                                 extPerms.setInstance(instance);
1613                                 extPerms.setType(app.getNameSpace() + "." + type);
1614                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1615                                 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1616                                 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1617                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1618                                 ResponseEntity<String> updatePermResponse = template.exchange(
1619                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1620                                                 HttpMethod.PUT, entity, String.class);
1621                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
1622                         } catch(HttpClientErrorException e){
1623                                 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1624                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1625                                 throw e;
1626                         } catch (Exception e) {
1627                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
1628                                 throw e;
1629                         }
1630                 }
1631         }
1632
1633         @SuppressWarnings("unchecked")
1634         @Override
1635         @Transactional(rollbackFor = Exception.class)
1636         public boolean deleteCentralRoleFunction(String code, EPApp app) {
1637                 boolean deleteFunctionResponse = false;
1638                 try {
1639                         final Map<String, String> params = new HashMap<>();
1640                         params.put(FUNCTION_CODE_PARAMS, code);
1641                         params.put(APP_ID, String.valueOf(app.getId()));
1642                         List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1643                                         .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1644                         CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1645                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1646                                 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1647                                 // Delete role function dependency records
1648                                 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1649                         }
1650                         dataAccessService.deleteDomainObject(appFunctionCode, null);
1651                         deleteFunctionResponse = true;
1652                 } catch (Exception e) {
1653                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1654                 }
1655                 return deleteFunctionResponse;
1656         }
1657
1658         /**
1659          * It deletes app function record in portal 
1660          * 
1661          * @param code
1662          * @param app
1663          */
1664         private void deleteAppRoleFunctions(String code, EPApp app) {
1665                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1666                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1667         }
1668         
1669         /**
1670          * 
1671          * It deletes permission in the external auth system  
1672          * 
1673          * @param domainCentralRoleFunction
1674          * @param app
1675          * @throws Exception
1676          */
1677         private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1678                         throws Exception {
1679                 try {
1680                         ObjectMapper mapper = new ObjectMapper();
1681                         ExternalAccessPerms extPerms = new ExternalAccessPerms();
1682                         String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1683                         String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1684                         String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1685                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1686                         extPerms.setAction(actionValue);
1687                         extPerms.setInstance(instanceValue);
1688                         extPerms.setType(app.getNameSpace() + "." + checkType);
1689                         extPerms.setDescription(domainCentralRoleFunction.getName());
1690                         String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1691                         HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1692                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1693                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1694                         ResponseEntity<String> delPermResponse = template
1695                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1696                                                         + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1697                         logger.debug(EELFLoggerDelegate.debugLogger,
1698                                         "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1699                                         deleteRoleFunction, delPermResponse.getStatusCode().value());
1700                 } catch(HttpClientErrorException e){
1701                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1702                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1703                 } catch (Exception e) {
1704                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1705                                 logger.debug(EELFLoggerDelegate.debugLogger,
1706                                                 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
1707                                                 e.getMessage());
1708                         } else {
1709                                 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1710                         }
1711                 }
1712         }
1713
1714         @Override
1715         public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1716                 boolean response = false;
1717                 String message = "";
1718                 try {
1719                         EPApp app = getApp(uebkey).get(0);
1720                         addRoleInEcompDB(saveRole, app);
1721                         response = true;
1722                 } catch (Exception e) {
1723                         message = e.getMessage();
1724                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1725                 }
1726                 return new ExternalRequestFieldsValidator(response,message);
1727         }
1728
1729         @SuppressWarnings("unchecked")
1730         @Override
1731         public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1732                 Session localSession = sessionFactory.openSession();
1733                 Transaction transaction = null;
1734                 boolean result = false;
1735                 try {
1736                         List<EPRole> epRoleList = null;
1737                         EPApp app = getApp(uebkey).get(0);
1738                         final Map<String, String> deleteRoleParams = new HashMap<>();
1739                         deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1740                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1741                                 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1742                         } else {
1743                                 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1744                                 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
1745                         }
1746                         if (!epRoleList.isEmpty()) {
1747                                 transaction = localSession.beginTransaction();
1748                                 // Delete app role functions before deleting role
1749                                 deleteRoleFunction(app, epRoleList);
1750                                 if (app.getId() == 1) {
1751                                         // Delete fn_user_ role
1752                                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1753                                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1754                                         boolean isPortalRequest = false;
1755                                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1756                                 }
1757                                 deleteRoleInExternalAuthSystem(epRoleList, app);
1758                                 transaction.commit();
1759                                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1760                                 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1761                         }
1762                         result = true;
1763                 } catch (Exception e) {
1764                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1765                         result = false;
1766                 } finally {
1767                         localSession.close();
1768                 }
1769                 return result;
1770         }
1771         
1772         /**
1773          * 
1774          * It deletes role for application in external auth system 
1775          * 
1776          * @param epRoleList contains role information
1777          * @param app contains application information
1778          * @throws Exception
1779          */
1780         private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1781                 ResponseEntity<String> deleteResponse;
1782                 ResponseEntity<String> res = getNameSpaceIfExists(app);
1783                 if (res.getStatusCode() == HttpStatus.OK) {
1784                 // Delete Role in External System
1785                 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1786                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1787                 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1788                 if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1789                         EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1790                         logger.error(EELFLoggerDelegate.errorLogger,
1791                                         "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1792                                         deleteResponse.getBody());
1793                 }
1794                 logger.debug(EELFLoggerDelegate.debugLogger,
1795                                 "deleteRoleForApplication: about to commit the transaction");
1796                 }
1797         }
1798
1799         /**
1800          * 
1801          * It deletes application user role in external auth system
1802          * 
1803          * @param role
1804          * @param app
1805          * @param LoginId
1806          * @throws Exception
1807          */
1808         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1809                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1810                 HttpEntity<String> entity = new HttpEntity<>(headers);
1811                 getNameSpaceIfExists(app);
1812                 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1813                 ResponseEntity<String> getResponse = template
1814                                 .exchange(
1815                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1816                                                                 + LoginId
1817                                                                 + SystemProperties
1818                                                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1819                                                                 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1820                                                 HttpMethod.GET, entity, String.class);
1821                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1822                 if (getResponse.getStatusCode().value() != 200) {
1823                         throw new ExternalAuthSystemException(getResponse.getBody());
1824                 }
1825                 String res = getResponse.getBody();
1826                 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1827                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1828                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1829                         ResponseEntity<String> deleteResponse = template
1830                                         .exchange(
1831                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1832                                                                         + "userRole/" + LoginId
1833                                                                         + SystemProperties
1834                                                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1835                                                                         + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1836                                                         HttpMethod.DELETE, userRoleentity, String.class);
1837                         if (deleteResponse.getStatusCode().value() != 200) {
1838                                 throw new ExternalAuthSystemException("Failed to delete user role");
1839                         }
1840                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1841                 }
1842         }
1843
1844         @SuppressWarnings("unchecked")
1845         @Override
1846         public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1847                 List<CentralV2Role> roleList = new ArrayList<>();
1848                 try {
1849                         List<EPApp> app = getApp(uebkey);
1850                         final Map<String, Long> params = new HashMap<>();
1851                         // check if portal
1852                         Long appId = null;
1853                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1854                                 appId = app.get(0).getId();
1855                         }
1856                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
1857                         Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1858                         Criterion appIdCrt;
1859                         if (appId == null)
1860                                 appIdCrt = Restrictions.isNull("appId");
1861                         else
1862                                 appIdCrt = Restrictions.eq("appId", appId);
1863                         Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1864                         restrictionsList.add(andCrit);
1865                         List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1866                         roleList = createCentralRoleObject(app, epRole, roleList, params);
1867                         List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1868                         if (globalRoleList.size() > 0)
1869                                 roleList.addAll(globalRoleList);
1870                 } catch (Exception e) {
1871                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1872                         throw e;
1873                 }
1874                 return roleList;
1875
1876         }
1877
1878         @Override
1879         @Transactional(rollbackFor = Exception.class)
1880         public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1881                 Session localSession = sessionFactory.openSession();
1882                 String message = "";
1883                 Transaction transaction = null;
1884                 boolean response = false;
1885                 EPApp app = null;
1886                 try {
1887                         transaction = localSession.beginTransaction();
1888                         List<EPRole> epRoleList = null;
1889                         app = getApp(uebkey).get(0);
1890                         if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1891                                 epRoleList = getPortalAppRoleInfo(roleId);
1892                         } else{
1893                                 epRoleList = getPartnerAppRoleInfo(roleId, app);
1894                         }
1895                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1896                                 // Delete User Role in External System before deleting role
1897                                 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);        
1898                         }
1899                         // Delete user app roles
1900                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1901                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1902                         boolean isPortalRequest = false;
1903                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1904                         transaction.commit();
1905                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1906                                 // Final call to delete role once all dependencies has been deleted
1907                                 deleteRoleInExternalAuthSystem(epRoleList, app);
1908                         }
1909                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);            
1910                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1911                         response = true;
1912                 } catch(HttpClientErrorException e){
1913                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1914                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1915                         message = e.getMessage();
1916                 } catch (Exception e) {
1917                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1918                         EcompPortalUtils.rollbackTransaction(transaction,
1919                                         "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1920                         message = e.getMessage();
1921                 } finally {
1922                         localSession.close();
1923                 }
1924                 return new ExternalRequestFieldsValidator(response,message);
1925         }
1926         
1927         @Override
1928         @SuppressWarnings("unchecked")
1929         @Transactional
1930         public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1931                 try {
1932
1933                         // get Permissions from External Auth System
1934                         JSONArray extPerms = getExtAuthPermissions(app);
1935                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1936
1937                         // get functions in DB
1938                         final Map<String, Long> params = new HashMap<>();
1939                         final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1940                         params.put(APP_ID, app.getId());
1941                         List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1942                                         null);
1943                         if (!appFunctions.isEmpty()) {
1944                                 for (CentralV2RoleFunction roleFunc : appFunctions) {
1945                                         roleFuncMap.put(roleFunc.getCode(), roleFunc);
1946                                 }
1947                         }
1948                         
1949                         // get Roles for portal in DB
1950                         List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1951                         final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1952                         for(EPRole epRole : portalRoleList){
1953                                 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1954                         }
1955                         
1956                         // get Roles in DB
1957                         final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
1958                         
1959                         // store External Permissions with Pipe and without Pipe (just instance)
1960                         final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1961                         final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1962                         for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1963                                 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1964                                 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1965                                 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1966                         }
1967
1968                         // Add if new functions and app role functions were added in
1969                         // external auth system
1970                         for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1971                                 String code = permsDetail.getInstance();
1972                                 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1973                                 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1974                                                 getFunctionCodeKey);
1975                                 List<String> roles = permsDetail.getRoles();
1976                                 if (roles != null) {
1977                                         // Check if function has any roles and which does not exist
1978                                         // in External Auth System. If exists delete in local
1979                                         addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
1980                                 }
1981                         }
1982
1983                         // Check if function does exits in External Auth System but exits in
1984                         // local then delete function and its dependencies
1985                         for (CentralV2RoleFunction roleFunc : appFunctions) {
1986                                 try {
1987                                         ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1988                                                         .get(roleFunc.getCode());
1989                                         if (null == getFunctionCodeContainsPipeKey) {
1990                                                 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1991                                                 if (null == getFunctionCodeKey) {
1992                                                         deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1993                                                 }
1994                                         }
1995                                 } catch (Exception e) {
1996                                         logger.error(EELFLoggerDelegate.errorLogger,
1997                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1998
1999                                 }
2000                         }
2001
2002                         logger.debug(EELFLoggerDelegate.debugLogger,
2003                                         "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
2004                 } catch (Exception e) {
2005                         logger.error(EELFLoggerDelegate.errorLogger,
2006                                         "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
2007
2008                 }
2009         }
2010
2011         @SuppressWarnings("unchecked")
2012         private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
2013                         List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
2014                         throws Exception {
2015                 if (!roleFunctionList.isEmpty()) {
2016                         final Map<String, String> appRoleFuncParams = new HashMap<>();
2017                         final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
2018                         final Map<String, String> currentRolesInExtSystem = new HashMap<>();
2019                         appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
2020                         appRoleFuncParams.put("appId", String.valueOf(app.getId()));
2021                         List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
2022                                         appRoleFuncParams, null);
2023                         for (LocalRole localRole : localRoleList) {
2024                                 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
2025                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
2026                         }
2027                         for (String addRole : roles) {
2028                                 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
2029                         }
2030                         for (String extAuthrole : roles) {
2031                                 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
2032                                 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
2033                                 if (isNameSpaceMatching) {
2034                                         if (!currentAppRoleFunctionsMap
2035                                                         .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
2036                                                 EPRole localAddFuntionRole = currentRolesInDB
2037                                                                 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
2038                                                 if (localAddFuntionRole == null) {
2039                                                         checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
2040                                                 } else {
2041                                                         EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2042                                                         addAppRoleFunc.setAppId(app.getId());
2043                                                         addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2044                                                         addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
2045                                                         dataAccessService.saveDomainObject(addAppRoleFunc, null);
2046                                                 }
2047                                         }
2048                                         // This block is to save global role function if exists
2049                                 } else {
2050                                         String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
2051                                         boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
2052                                         if (checkIfGlobalRoleExists) {
2053                                                 final Map<String, Long> params = new HashMap<>();
2054                                                 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
2055                                                 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
2056                                                 params.put("appId", app.getId());
2057                                                 params.put("roleId", role.getId());
2058                                                 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);                               
2059                                                 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
2060                                                 if (role != null && !checkIfRoleFunctionExists) {
2061                                                         addGlobalRoleFunctions.setAppId(app.getId());
2062                                                         addGlobalRoleFunctions.setRoleId(role.getId());
2063                                                         if (!app.getId().equals(role.getAppRoleId())) {
2064                                                                 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
2065                                                         } else {
2066                                                                 addGlobalRoleFunctions.setRoleAppId(null);
2067                                                         }
2068                                                         addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
2069                                                         dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
2070                                                 }
2071                                         }
2072                                 }
2073                         }
2074                         for (LocalRole localRoleDelete : localRoleList) {
2075                                 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
2076                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2077                                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2078                                                         APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
2079                                                                         + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
2080                                                         null);
2081                                 }
2082                         }
2083                 }
2084         }
2085
2086         private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2087                 logger.debug(EELFLoggerDelegate.debugLogger,
2088                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
2089                                 roleFunc.getCode());
2090                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2091                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2092                 logger.debug(EELFLoggerDelegate.debugLogger,
2093                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
2094                                 roleFunc.getCode());
2095
2096                 logger.debug(EELFLoggerDelegate.debugLogger,
2097                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
2098                                 roleFunc.getCode());
2099                 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2100                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2101                 logger.debug(EELFLoggerDelegate.debugLogger,
2102                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
2103                                 roleFunc.getCode());
2104         }
2105
2106         private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2107                         List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2108                 if (!currentRolesInDB.containsKey(
2109                                 roleList.substring(app.getNameSpace().length() + 1))) {
2110                         Role role = addRoleInDBIfDoesNotExists(app,
2111                                         roleList.substring(app.getNameSpace().length() + 1));
2112                         addIfRoleDescriptionNotExitsInExtSystem(role, app);
2113                         if (!roleFunctionList.isEmpty()) {
2114                                 try {
2115                                         if (!roleFunctionList.isEmpty()) {
2116                                                 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2117                                                 addAppRoleFunc.setAppId(app.getId());
2118                                                 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2119                                                 addAppRoleFunc.setRoleId(role.getId());
2120                                                 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2121                                         }
2122                                 } catch (Exception e) {
2123                                         logger.error(EELFLoggerDelegate.errorLogger,
2124                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
2125                                                         e);
2126                                 }
2127                         }
2128                 }
2129         }
2130
2131         @SuppressWarnings("unchecked")
2132         private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2133                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2134                 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2135                                 getFunctionCodeKey);
2136                 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2137                 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2138                 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2139                 List<CentralV2RoleFunction> roleFunctionList = null;
2140                 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2141                                 null);
2142                 if (roleFunctionList.isEmpty()) {
2143                         appSyncFuncsParams.put("functionCd", code);
2144                         roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2145                                         null);
2146                 }
2147                 return roleFunctionList;
2148         }
2149
2150         private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2151                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
2152                         ) {
2153                 String finalFunctionCodeVal = "";       
2154                 if (null == getFunctionCodeKey) {
2155                         finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2156                         CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2157                         // If function does not exist in local then add!
2158                         if (null == checkIfCodeStillExits) {
2159                                 logger.debug(EELFLoggerDelegate.debugLogger,
2160                                                 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2161                                 addFunctionInEcompDB(app, permsDetail, code);
2162                                 logger.debug(EELFLoggerDelegate.debugLogger,
2163                                                 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2164                         }
2165                 }
2166                 return finalFunctionCodeVal;
2167         }
2168
2169         @SuppressWarnings("unchecked")
2170         @Override
2171         public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
2172                 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2173                 List<EPRole> getCurrentRoleList = null;
2174                 final Map<String, Long> appParams = new HashMap<>();
2175                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2176                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2177                 } else {
2178                         appParams.put("appId", app.getId());
2179                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2180                 }
2181                 for (EPRole role : getCurrentRoleList) {
2182                         currentRolesInDB.put(role.getName()
2183                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2184                 }
2185                 return currentRolesInDB;
2186         }
2187
2188         private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
2189                         throws IOException{
2190                 ExternalAccessPermsDetail permDetails = null;
2191                 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2192                 for (int i = 0; i < extPerms.length(); i++) {
2193                         String description = null;
2194                         if (extPerms.getJSONObject(i).has("description")) {
2195                                 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2196                         } else {
2197                                 description = extPerms.getJSONObject(i).getString("instance");
2198                         }
2199                         if (extPerms.getJSONObject(i).has("roles")) {
2200                                 ObjectMapper rolesListMapper = new ObjectMapper();
2201                                 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2202                                 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2203                                                 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2204                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2205                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2206                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2207                                                                 + extPerms.getJSONObject(i).getString("action"),
2208                                                 extPerms.getJSONObject(i).getString("action"), list, description);
2209                                 permsDetailList.add(permDetails);
2210                         } else {
2211                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2212                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2213                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2214                                                                 + extPerms.getJSONObject(i).getString("action"),
2215                                                 extPerms.getJSONObject(i).getString("action"), description);
2216                                 permsDetailList.add(permDetails);
2217                         }
2218                 }
2219                 return permsDetailList;
2220         }
2221
2222         private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2223                 ResponseEntity<String> response = null;
2224                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2225                 HttpEntity<String> entity = new HttpEntity<>(headers);
2226                 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2227                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2228                 response = template
2229                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2230                                                 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2231
2232                 String res = response.getBody();
2233                 logger.debug(EELFLoggerDelegate.debugLogger,
2234                                 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2235                                 response.getBody());
2236                 JSONObject jsonObj = new JSONObject(res);
2237                 JSONArray extPerms = jsonObj.getJSONArray("perm");
2238                 for (int i = 0; i < extPerms.length(); i++) {
2239                         if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2240                                 extPerms.remove(i);
2241                                 i--;
2242                         }
2243                 }
2244                 return extPerms;
2245         }
2246         
2247         /**
2248          * 
2249          * Add function into local DB
2250          * 
2251          * @param app
2252          * @param permsDetail
2253          * @param code
2254          */
2255         private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2256                 try{
2257                 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2258                 addFunction.setAppId(app.getId());
2259                 addFunction.setCode(code);
2260                 addFunction.setName(permsDetail.getDescription());
2261                 dataAccessService.saveDomainObject(addFunction, null);
2262                 } catch(Exception e){
2263                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2264                 }
2265         }
2266
2267         /**
2268          * 
2269          * It updates description of a role in external auth system
2270          * 
2271          * @param role
2272          * @param app
2273          * @throws Exception
2274          */
2275         private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
2276                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2277                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2278                 try {
2279                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2280                         template.exchange(
2281                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2282                                         HttpMethod.PUT, entity, String.class);
2283                 } catch (HttpClientErrorException e) {
2284                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
2285                                         e);
2286                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2287                 } catch (Exception e) {
2288                         logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
2289                                         e);
2290                 }
2291         }
2292
2293         /**
2294          * 
2295          * While sync functions form external auth system if new role found we should add in local and return Role.class object
2296          * 
2297          * @param app
2298          * @param role
2299          * @return
2300          */
2301         @SuppressWarnings("unchecked")
2302         private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2303                 Role setNewRole = new Role();
2304                 try {
2305                         // functions can have new role created in External Auth System prevent
2306                         // duplication here
2307                         boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2308                         final Map<String, String> getRoleByNameParams = new HashMap<>();
2309                         List<EPRole> getRoleCreated = null;
2310                         getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2311                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2312                                 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2313                                 List<EPRole> roleCreated = dataAccessService
2314                                                 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2315                                 if (!isCreated) {
2316                                         EPRole epUpdateRole = roleCreated.get(0);
2317                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
2318                                         dataAccessService.saveDomainObject(epUpdateRole, null);
2319                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2320                                                         getRoleByNameParams, null);
2321                                 } else {
2322                                         getRoleCreated = roleCreated;
2323                                 }
2324                         } else {
2325                                 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2326                                                 null);
2327                         }
2328                         if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2329                                 EPRole roleObject = getRoleCreated.get(0);
2330                                 setNewRole.setId(roleObject.getId());
2331                                 setNewRole.setName(roleObject.getName());
2332                                 setNewRole.setActive(roleObject.getActive());
2333                                 setNewRole.setPriority(roleObject.getPriority());
2334                         }
2335                 } catch (Exception e) {
2336                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2337                 }
2338                 return setNewRole;
2339         }
2340
2341         @SuppressWarnings("unchecked")
2342         private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2343                 boolean isCreated = false;
2344                 final Map<String, String> roleParams = new HashMap<>();
2345                 roleParams.put(APP_ROLE_NAME_PARAM, role);
2346                 List<EPRole> roleCreated = null;
2347                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2348                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2349                                         null);
2350                 } else {
2351                         roleParams.put("appId", String.valueOf(app.getId()));
2352                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2353                                         null);
2354                 }
2355                 if (roleCreated == null || roleCreated.isEmpty()) {
2356                         roleParams.put("appId", String.valueOf(app.getId()));
2357                         EPRole epRoleNew = new EPRole();
2358                         epRoleNew.setActive(true);
2359                         epRoleNew.setName(role);
2360                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2361                                 epRoleNew.setAppId(null);
2362                         } else {
2363                                 epRoleNew.setAppId(app.getId());
2364                         }
2365                         dataAccessService.saveDomainObject(epRoleNew, null);
2366                         isCreated = false;
2367                 } else {
2368                         isCreated = true;
2369                 }
2370                 return isCreated;
2371         }
2372
2373         @Override
2374         @SuppressWarnings("unchecked")
2375         public Integer bulkUploadFunctions(String uebkey) throws Exception {
2376                 EPApp app = getApp(uebkey).get(0);
2377                 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2378                 CentralV2RoleFunction cenRoleFunc = null;
2379                 Integer functionsAdded = 0;
2380                 try {
2381                         for (RoleFunction roleFunc : roleFuncList) {
2382                                 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2383                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2384                                 functionsAdded++;
2385                         }
2386                 } catch(HttpClientErrorException e){
2387                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2388                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2389                 } catch (Exception e) {
2390                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2391                 }
2392                 return functionsAdded;
2393         }
2394
2395         @Override
2396         public Integer bulkUploadRoles(String uebkey) throws Exception {
2397                 List<EPApp> app = getApp(uebkey);
2398                 List<EPRole> roles = getAppRoles(app.get(0).getId());
2399                 List<CentralV2Role> cenRoleList = new ArrayList<>();
2400                 final Map<String, Long> params = new HashMap<>();
2401                 Integer rolesListAdded = 0;
2402                 try {
2403                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2404                         ObjectMapper mapper = new ObjectMapper();
2405                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2406                         String roleList = mapper.writeValueAsString(cenRoleList);
2407                         List<Role> roleObjectList = mapper.readValue(roleList,
2408                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2409                         for (Role role : roleObjectList) {
2410                                 addRoleInExternalSystem(role, app.get(0));
2411                                 rolesListAdded++;
2412                         }
2413                 } catch (Exception e) {
2414                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2415                         throw e;
2416                 }
2417                 return rolesListAdded;
2418         }
2419
2420         /**
2421          * It creating new role in external auth system while doing bulk upload
2422          * 
2423          * @param role
2424          * @param app
2425          * @throws Exception
2426          */
2427         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2428                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2429                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2430                 try {
2431                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2432                         template.exchange(
2433                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2434                                         HttpMethod.POST, entity, String.class);
2435                 } catch(HttpClientErrorException e){
2436                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
2437                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2438                 } catch (Exception e) {
2439                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2440                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2441                         } else {
2442                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2443                         }
2444                 }
2445         }
2446
2447         @Override
2448         @SuppressWarnings("unchecked")
2449         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2450                 EPApp app = getApp(uebkey).get(0);
2451                 List<EPRole> roles = getAppRoles(app.getId());
2452                 final Map<String, Long> params = new HashMap<>();
2453                 Integer roleFunctions = 0;
2454                 try {
2455                         for (EPRole role : roles) {
2456                                 params.put("roleId", role.getId());
2457                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2458                                                 params, null);
2459                                 if (!appRoleFunc.isEmpty()) {
2460                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2461                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2462                                                 roleFunctions++;
2463                                         }
2464                                 }
2465                         }
2466                 } catch(HttpClientErrorException e){
2467                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2468                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2469                 } catch (Exception e) {
2470                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2471                 }
2472                 return roleFunctions;
2473         }
2474         
2475         /**
2476          * Its adding a role function while doing bulk upload
2477          * 
2478          * @param addRoleFunc
2479          * @param role
2480          * @param app
2481          */
2482         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2483                 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2484                 ExternalAccessRolePerms extRolePerms = null;
2485                 ExternalAccessPerms extPerms = null;
2486                 ObjectMapper mapper = new ObjectMapper();
2487                 try {
2488                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2489
2490                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
2491                                         addRoleFunc.getFunctionName());
2492                         extRolePerms = new ExternalAccessRolePerms(extPerms,
2493                                         app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2494                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2495                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2496                         template.exchange(
2497                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2498                                         HttpMethod.POST, entity, String.class);
2499                 } catch (Exception e) {
2500                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2501                                 logger.error(EELFLoggerDelegate.errorLogger,
2502                                                 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
2503                         } else {
2504                                 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
2505                                                 e.getMessage());
2506                         }
2507                 }
2508         }
2509
2510         @Override
2511         public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
2512                 EPApp app = getApp(uebkey).get(0);
2513                 CentralV2RoleFunction cenRoleFunc = null;
2514                 for (RoleFunction roleFunction : roleFunctionsList) {
2515                         cenRoleFunc = new CentralV2RoleFunction(roleFunction.getCode(), roleFunction.getName());
2516                         addRoleFunctionInExternalSystem(cenRoleFunc, app);
2517                 }
2518         }
2519
2520         @Override
2521         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2522                 EPApp app = getApp(uebkey).get(0);
2523                 for (Role role : roleList) {
2524                         addRoleInExternalSystem(role, app);
2525                 }
2526         }
2527
2528         @SuppressWarnings("unchecked")
2529         @Override
2530         public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
2531                 EPApp app = getApp(uebkey).get(0);
2532                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2533                 for (Role role : roleList) {
2534                         try {
2535                                 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
2536                                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
2537                                 ObjectMapper roleFunctionsMapper = new ObjectMapper();
2538                                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
2539                                 while (itetaror.hasNext()) {
2540                                         Object nextValue = itetaror.next();
2541                                         RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
2542                                         roleFunctionListNew.add(roleFunction);
2543                                 }
2544                                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
2545                                                 .collect(Collectors.toList());
2546                                 for (RoleFunction roleFunction : listWithoutDuplicates) {
2547                                         String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
2548                                         ExternalAccessRolePerms extRolePerms = null;
2549                                         ExternalAccessPerms extPerms = null;
2550                                         ObjectMapper mapper = new ObjectMapper();
2551                                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
2552                                                         "*");
2553                                         extRolePerms = new ExternalAccessRolePerms(extPerms,
2554                                                         app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2555                                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2556                                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2557                                         template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2558                                                         + "role/perm", HttpMethod.PUT, entity, String.class);
2559                                 }
2560                         } catch (Exception e) {
2561                                 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2562                                         logger.error(EELFLoggerDelegate.errorLogger,
2563                                                         "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
2564                                 } else {
2565                                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
2566                                                         e);
2567                                 }
2568                         }
2569
2570                 }
2571         }
2572
2573         @Override
2574         @Transactional
2575         public void syncApplicationRolesWithEcompDB(EPApp app) {
2576                 try {
2577                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2578                         //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
2579                         syncRoleFunctionFromExternalAccessSystem(app);
2580                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");     
2581                         
2582                         ObjectMapper mapper = new ObjectMapper();
2583                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2584                         // Get Permissions from External Auth System
2585                         JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2586                         
2587                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2588                         List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
2589                                         mapper, extRole);
2590                         
2591                         List<EPRole> finalRoleList = new ArrayList<>();
2592                         for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2593                                 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2594                                 finalRoleList.add(ecompRole);
2595                         }
2596
2597                         List<EPRole> applicationRolesList;
2598                         applicationRolesList = getAppRoles(app.getId());
2599                         List<String> applicationRoleIdList = new ArrayList<>();
2600                         for (EPRole applicationRole : applicationRolesList) {
2601                                 applicationRoleIdList.add(applicationRole.getName());
2602                         }
2603
2604                         List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2605                         for (EPRole aafRole : finalRoleList) {
2606                                 if (!applicationRoleIdList.contains(aafRole.getName())) {
2607                                         roleListToBeAddInEcompDB.add(aafRole);
2608                                 }
2609                         }
2610
2611                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2612                         // Check if roles exits in external Access system and if not make inactive in DB
2613                         inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2614
2615                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
2616                         // It checks properties in the external auth system app role description and updates role in local
2617                         checkAndUpdateRoleInDB(app, finalRoleList);
2618
2619                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2620                         // Add new roles in DB and updates role description in External Auth System 
2621                         addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2622                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2623                 } catch (HttpClientErrorException e) {
2624                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2625                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2626                 } catch (Exception e) {
2627                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2628                 }
2629         }
2630
2631         /**
2632          * 
2633          * It adds new roles in DB and updates description in External Auth System
2634          * 
2635          * @param app
2636          * @param roleListToBeAddInEcompDB
2637          */
2638         @SuppressWarnings("unchecked")
2639         private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2640                 EPRole roleToBeAddedInEcompDB;
2641                 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2642                         try {
2643                                 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2644                                 if (app.getId() == 1) {
2645                                         roleToBeAddedInEcompDB.setAppRoleId(null);
2646                                 }
2647                                 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2648                                 List<EPRole> getRoleCreatedInSync = null;
2649                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2650                                         final Map<String, String> globalRoleParams = new HashMap<>();
2651                                         globalRoleParams.put("appId", String.valueOf(app.getId()));
2652                                         globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2653                                         getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2654                                         EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2655                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
2656                                         dataAccessService.saveDomainObject(epUpdateRole, null);
2657                                 }
2658                                 List<EPRole> roleList = new ArrayList<>();
2659                                 final Map<String, String> params = new HashMap<>();
2660
2661                                 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2662                                 boolean isPortalRole = false;
2663                                 if (app.getId() == 1) {
2664                                         isPortalRole = true;
2665                                         roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2666                                 } else {
2667                                         isPortalRole = false;
2668                                         params.put(APP_ID, app.getId().toString());
2669                                         roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
2670                                 }
2671                                 EPRole role = roleList.get(0);
2672                                 Role aaFrole = new Role();
2673                                 aaFrole.setId(role.getId());
2674                                 aaFrole.setActive(role.getActive());
2675                                 aaFrole.setPriority(role.getPriority());
2676                                 aaFrole.setName(role.getName());
2677                                 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2678                         } catch (Exception e) {
2679                                 logger.error(EELFLoggerDelegate.errorLogger,
2680                                                 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2681                         }
2682                 }
2683         }
2684
2685         /**
2686          * 
2687          * It checks description in External Auth System if found any changes updates in DB
2688          * 
2689          * @param app
2690          * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
2691          */
2692         @SuppressWarnings("unchecked")
2693         private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
2694                 for (EPRole roleItem : finalRoleList) {
2695                         final Map<String, String> roleParams = new HashMap<>();
2696                         List<EPRole> currentList = null;
2697                         roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
2698                         if (app.getId() == 1) {
2699                                 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2700                         } else {
2701                                 roleParams.put(APP_ID, app.getId().toString());
2702                                 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
2703                         }
2704
2705                         if (!currentList.isEmpty()) {
2706                                 try {
2707                                         Boolean aafRoleActive;
2708                                         Boolean localRoleActive;
2709                                         boolean result;
2710                                         aafRoleActive = Boolean.valueOf(roleItem.getActive());
2711                                         localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2712                                         result = aafRoleActive.equals(localRoleActive);
2713                                         EPRole updateRole = currentList.get(0);
2714
2715                                         if (!result) {
2716                                                 updateRole.setActive(roleItem.getActive());
2717                                                 dataAccessService.saveDomainObject(updateRole, null);
2718                                         }
2719                                         if (roleItem.getPriority() != null
2720                                                         && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2721                                                 updateRole.setPriority(roleItem.getPriority());
2722                                                 dataAccessService.saveDomainObject(updateRole, null);
2723                                         }
2724                                 } catch (Exception e) {
2725                                         logger.error(EELFLoggerDelegate.errorLogger,
2726                                                         "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2727                                 }
2728                         }
2729                 }
2730         }
2731         /**
2732          * 
2733          * It de-activates application roles in DB if not present in External Auth system  
2734          * 
2735          * @param app
2736          * @param finalRoleList contains list of current roles present in External Auth System
2737          * @param applicationRolesList contains list of current roles present in DB
2738          */
2739         @SuppressWarnings("unchecked")
2740         private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2741                         List<EPRole> applicationRolesList) {
2742                 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2743                 for (EPRole extrole : finalRoleList) {
2744                         checkRolesInactive.put(extrole.getName(), extrole);
2745                 }
2746                 for (EPRole role : applicationRolesList) {
2747                         try {
2748                                 final Map<String, String> extRoleParams = new HashMap<>();
2749                                 List<EPRole> roleList = null;
2750                                 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2751                                 if (!checkRolesInactive.containsKey(role.getName())) {
2752                                         if (app.getId() == 1) {
2753                                                 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2754                                         } else {
2755                                                 extRoleParams.put(APP_ID, app.getId().toString());
2756                                                 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
2757                                         }
2758                                         if(!roleList.isEmpty()) {
2759                                                 EPRole updateRoleInactive = roleList.get(0);
2760                                                 updateRoleInactive.setActive(false);
2761                                                 dataAccessService.saveDomainObject(updateRoleInactive, null);
2762                                         }
2763                                 }
2764                         } catch (Exception e) {
2765                                 logger.error(EELFLoggerDelegate.errorLogger,
2766                                                 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2767                         }
2768                 }
2769         }
2770         
2771         @Override
2772         @SuppressWarnings("unchecked")
2773         public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
2774                         ObjectMapper mapper, JSONArray extRole)
2775                         throws IOException {
2776                 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2777                 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
2778                 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); 
2779                 List<String> functionCodelist = new ArrayList<>();
2780                 for (int i = 0; i < extRole.length(); i++) {
2781                         ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2782                         EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2783                         JSONObject Role = (JSONObject) extRole.get(i);
2784                         if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2785                                 ApplicationRole.setActive("true");
2786                                 ApplicationRole.setAppId(IS_NULL_STRING);
2787                                 ApplicationRole.setPriority(IS_NULL_STRING);
2788                                 ApplicationRole.setAppRoleId(IS_NULL_STRING);
2789                                 String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
2790                                 ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
2791                         } else {
2792                                 String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2793                                 ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
2794                         }
2795
2796                         SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2797                         if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2798                                 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2799                                 for (int j = 0; j < extPerm.length(); j++) {
2800                                         JSONObject perms = extPerm.getJSONObject(j);
2801                                         boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"), app.getNameSpace());
2802                                         if (isNamespaceMatching) {
2803                                                 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2804                                                                 perms.getString("instance"), perms.getString("action"));
2805                                                 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2806                                                 functionCodelist.add(ePAppRoleFunction.getCode());
2807                                                 externalAccessPermsOfRole.add(externalAccessPerms);
2808                                         }
2809
2810                                 }
2811                         }
2812
2813                         if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
2814                                 externalRoleDetail.setActive(false);
2815                         } else {
2816                                 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
2817                         }
2818                         externalRoleDetail.setName(ApplicationRole.getName());
2819
2820                         if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
2821                                 externalRoleDetail.setAppId(null);
2822                         } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
2823                                 externalRoleDetail.setAppId(app.getId());
2824                         } else {
2825                                 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
2826                         }
2827
2828                         if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
2829                                 externalRoleDetail.setPriority(null);
2830                         } else {
2831                                 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
2832                         }
2833
2834                         if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
2835                                 externalRoleDetail.setAppRoleId(null);
2836                         }
2837
2838                         // get role functions from DB
2839                         final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2840                         if (!ApplicationRole.getId().equals(IS_NULL_STRING)) {
2841                                 final Map<String, Long> appRoleFuncsParams = new  HashMap<>();
2842                                 appRoleFuncsParams.put("appId", app.getId());
2843                                 appRoleFuncsParams.put("roleId", Long.valueOf(ApplicationRole.getId()));
2844                                 List<EPAppRoleFunction> appRoleFunctions = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2845                                 if (!appRoleFunctions.isEmpty()) {
2846                                         for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2847                                                 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2848                                         }
2849                                 }
2850                         }
2851
2852                         if (!externalAccessPermsOfRole.isEmpty()) {
2853                                 // Adding functions to role
2854                                 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2855                                         EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2856                                         if (checkRoleFunctionExits == null) {
2857                                                 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2858                                                                 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2859                                                                 + externalpermission.getAction();
2860                                                 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2861                                                 if (checkRoleFunctionPipeExits == null) {
2862                                                         try {
2863                                                                 final Map<String, String> appFuncsParams = new  HashMap<>();
2864                                                                 appFuncsParams.put("appId", String.valueOf(app.getId()));
2865                                                                 appFuncsParams.put("functionCd", externalpermission.getInstance());
2866                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
2867                                                                                 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2868                                                                                 externalpermission.getInstance());
2869                                                                 List<CentralV2RoleFunction> roleFunction = null;
2870                                                                 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
2871                                                                 if (roleFunction.isEmpty()) {
2872                                                                         appFuncsParams.put("functionCd", funcCode);
2873                                                                         roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
2874                                                                 }
2875                                                                 if (!roleFunction.isEmpty()) {
2876                                                                         EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2877                                                                         apRoleFunction.setAppId(app.getId());
2878                                                                         apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
2879                                                                         apRoleFunction.setCode(roleFunction.get(0).getCode());
2880                                                                         dataAccessService.saveDomainObject(apRoleFunction, null);
2881                                                                 }
2882                                                         } catch (Exception e) {
2883                                                                 logger.error(EELFLoggerDelegate.errorLogger,
2884                                                                                 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2885                                                         }
2886                                                 }
2887                                         }
2888                                 }
2889                         }
2890                         externalRoleDetailsList.add(externalRoleDetail);
2891                 }
2892                 return externalRoleDetailsList;
2893         }
2894
2895         @Override
2896         public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2897                 ResponseEntity<String> response = null;
2898                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2899                 HttpEntity<String> entity = new HttpEntity<>(headers);
2900                 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2901                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2902                 response = template
2903                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2904                                                 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2905                 String res = response.getBody();
2906                 logger.debug(EELFLoggerDelegate.debugLogger,
2907                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2908                                 res);
2909                 JSONObject jsonObj = new JSONObject(res);
2910                 JSONArray extRole = jsonObj.getJSONArray("role");
2911                 for (int i = 0; i < extRole.length(); i++) {
2912                         if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2913                                         || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2914                                         || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2915                                                         && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
2916                                 extRole.remove(i);
2917                                 i--;
2918                         }                       
2919                 }
2920                 return extRole;
2921         }
2922         
2923         @Override
2924         public JSONArray getAllUsersByRole(String roleName) throws Exception{
2925                 ResponseEntity<String> response = null;
2926                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2927                 HttpEntity<String> entity = new HttpEntity<>(headers);
2928                 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
2929                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2930                 response = template
2931                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2932                                                 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
2933                 String res = response.getBody();
2934                 logger.debug(EELFLoggerDelegate.debugLogger,
2935                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2936                                 res);
2937                 JSONObject jsonObj = new JSONObject(res);
2938                 JSONArray extRole = jsonObj.getJSONArray("userRole");
2939                 
2940                 return extRole;
2941         }
2942
2943         /**
2944          * 
2945          * It converts from ExternalRoleDetails.class object to EPRole.class object
2946          * 
2947          * @param externalRoleDetails
2948          * @return EPRole object
2949          */
2950         private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2951                 EPRole role = new EPRole();
2952                 role.setActive(externalRoleDetails.isActive());
2953                 role.setAppId(externalRoleDetails.getAppId());
2954                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2955                 role.setName(externalRoleDetails.getName());
2956                 role.setPriority(externalRoleDetails.getPriority());
2957                 return role;
2958         }
2959
2960         @SuppressWarnings("unchecked")
2961         @Override
2962         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2963                 EPApp app = getApp(uebkey).get(0);
2964                 final Map<String, String> params = new HashMap<>();
2965                 params.put("uebKey", app.getUebKey());
2966                 List<BulkUploadUserRoles> userRolesList = null;
2967                 Integer userRolesAdded = 0;
2968                 if (app.getCentralAuth()) {
2969                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2970                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2971                                 if(!userRolesUpload.getOrgUserId().equals("su1234")){
2972                                         addUserRoleInExternalSystem(userRolesUpload);
2973                                         userRolesAdded++;
2974                                 }
2975                         }
2976                 }
2977                 return userRolesAdded;
2978         }
2979
2980         /**
2981          * Its adding a user role in external auth system while doing bulk upload 
2982          * 
2983          * @param userRolesUpload
2984          */
2985         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2986                 try {
2987                         String name = "";
2988                         ObjectMapper mapper = new ObjectMapper();
2989                         if (EPCommonSystemProperties
2990                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2991                                 name = userRolesUpload.getOrgUserId()
2992                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2993                         }
2994                         ExternalAccessUser extUser = new ExternalAccessUser(name,
2995                                         userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2996                         String userRole = mapper.writeValueAsString(extUser);
2997                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2998                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2999                         template.exchange(
3000                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
3001                                         HttpMethod.POST, entity, String.class);
3002                 } catch(HttpClientErrorException e){
3003                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3004                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3005                 } catch (Exception e) {
3006                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3007                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3008                         } else {
3009                                 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3010                         }
3011                 }
3012         }
3013
3014         @Override
3015         public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
3016                 try {
3017                         String sql = ""; 
3018                         Query query = null;
3019                         
3020                         //It should delete only when it portal's roleId
3021                         if(appId.equals(PortalConstants.PORTAL_APP_ID)){
3022                         // Delete from fn_role_function
3023                         sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3024                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3025                         query = localSession.createSQLQuery(sql);
3026                         query.executeUpdate();
3027                         
3028                         // Delete from fn_role_composite
3029                         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3030                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3031                         query = localSession.createSQLQuery(sql);
3032                         query.executeUpdate();
3033                         }
3034                         
3035                         // Delete from ep_app_role_function
3036                         sql = "DELETE FROM ep_app_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 ep_role_notification
3042                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3043                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3044                         query = localSession.createSQLQuery(sql);
3045                         query.executeUpdate();
3046                         
3047                         // Delete from fn_user_pseudo_role
3048                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3049                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3050                         query = localSession.createSQLQuery(sql);
3051                         query.executeUpdate();
3052
3053                         // Delete form EP_WIDGET_CATALOG_ROLE
3054                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3055                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3056                         query = localSession.createSQLQuery(sql);
3057                         query.executeUpdate();
3058
3059                         // Delete form EP_WIDGET_CATALOG_ROLE
3060                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3061                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3062                         query = localSession.createSQLQuery(sql);
3063                         query.executeUpdate();
3064
3065                         if(!isPortalRequest) {
3066                                 // Delete form fn_menu_functional_roles
3067                                 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3068                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3069                                 query = localSession.createSQLQuery(sql);
3070                                 query.executeUpdate();  
3071                         }
3072                 } catch (Exception e) {
3073                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3074                         throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3075                 }
3076
3077         }
3078         
3079         @SuppressWarnings("unchecked")
3080         @Override
3081         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3082                 List<String> appMenuFunctionsList = null;
3083                 try {
3084                         EPApp app = getApp(uebkey).get(0);
3085                         final Map<String, Long> appParams = new HashMap<>();
3086                         appParams.put(APP_ID, app.getId());
3087                         appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3088                 } catch (Exception e) {
3089                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3090                         return appMenuFunctionsList;
3091                 }
3092                 return appMenuFunctionsList;
3093         }
3094
3095         @SuppressWarnings({ "unchecked"})
3096         @Override
3097         public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3098                 List<String> usersList = new ArrayList<>();
3099                 List<EcompUser> usersfinalList = new ArrayList<>();
3100                 try {
3101                         EPApp app = getApp(uebkey).get(0);
3102                         final Map<String, Long> appParams = new HashMap<>();
3103                         appParams.put("appId", app.getId());
3104                         List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3105                                         .executeNamedQuery("ApplicationUserRoles", appParams, null);
3106                         for (EcompUserRoles ecompUserRole : userList) {
3107                                 boolean found = false;
3108                                 Set<EcompRole> roles = null;
3109                                 for (EcompUser user : usersfinalList) {
3110                                         if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3111                                                 EcompRole ecompRole = new EcompRole();
3112                                                 ecompRole.setId(ecompUserRole.getRoleId());
3113                                                 ecompRole.setName(ecompUserRole.getRoleName());
3114                                                 roles = user.getRoles();
3115                                                 roles.add(ecompRole);
3116                                                 user.setRoles(roles);
3117                                                 found = true;
3118                                                 break;
3119                                         }
3120                                 }
3121
3122                                 if (!found) {
3123                                         EcompUser epUser = new EcompUser();
3124                                         epUser.setOrgId(ecompUserRole.getOrgId());
3125                                         epUser.setManagerId(ecompUserRole.getManagerId());
3126                                         epUser.setFirstName(ecompUserRole.getFirstName());
3127                                         epUser.setLastName(ecompUserRole.getLastName());
3128                                         epUser.setPhone(ecompUserRole.getPhone());
3129                                         epUser.setEmail(ecompUserRole.getEmail());
3130                                         epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3131                                         epUser.setOrgCode(ecompUserRole.getOrgCode());
3132                                         epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3133                                         epUser.setJobTitle(ecompUserRole.getJobTitle());
3134                                         epUser.setLoginId(ecompUserRole.getLoginId());
3135                                         epUser.setActive(true);
3136                                         roles = new HashSet<>();
3137                                         EcompRole ecompRole = new EcompRole();
3138                                         ecompRole.setId(ecompUserRole.getRoleId());
3139                                         ecompRole.setName(ecompUserRole.getRoleName());
3140                                         roles.add(ecompRole);
3141                                         epUser.setRoles(roles);
3142                                         usersfinalList.add(epUser);
3143                                 }
3144                         }
3145                         ObjectMapper mapper = new ObjectMapper();
3146
3147                         for (EcompUser u1 : usersfinalList) {
3148                                 String str = mapper.writeValueAsString(u1);
3149                                 usersList.add(str);
3150                         }
3151                 } catch (Exception e) {
3152                         logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3153                         throw e;
3154                 }
3155                 return usersfinalList;
3156         }
3157         
3158
3159         @Override
3160         public Role ConvertCentralRoleToRole(String result) {
3161                 ObjectMapper mapper = new ObjectMapper();
3162                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3163                 Role newRole = new Role();
3164                 try {
3165                         newRole = mapper.readValue(result, Role.class);
3166                 } catch (IOException e) {
3167                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3168                 }
3169                 if (newRole.getRoleFunctions() != null) {
3170                         @SuppressWarnings("unchecked")
3171                         Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3172                         Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3173                         Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3174                         while (itetaror.hasNext()) {
3175                                 Object nextValue = itetaror.next();
3176                                 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3177                                 roleFunctionListNew.add(roleFun);
3178                         }
3179                         newRole.setRoleFunctions(roleFunctionListNew);
3180                 }
3181                 return newRole;
3182         }
3183         
3184         @Override
3185         @SuppressWarnings("unchecked")
3186         public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3187                 Map<String, String> params = new HashMap<>();
3188                 params.put("userId", userId);
3189                 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3190                 try{
3191                         centralizedAppsList =  dataAccessService
3192                                         .executeNamedQuery("getCentralizedAppsOfUser", params, null);
3193                 }catch (Exception e) {
3194                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3195                 }
3196                 return centralizedAppsList;
3197         }
3198
3199         @SuppressWarnings("unchecked")
3200         public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3201                 Map<String, Long> params = new HashMap<>();
3202                 params.put("appId", appId);
3203                 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3204                 try {
3205                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3206                                         null);
3207                 } catch (Exception e) {
3208                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3209                 }
3210                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3211                 if (globalRoles.size() > 0)
3212                         rolesfinalList = finalListOfCentralRoles(globalRoles);
3213                 return rolesfinalList;
3214         }
3215
3216         @SuppressWarnings("unchecked")
3217         private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3218                 CentralV2Role finalGlobalrole = null;
3219                 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3220                 Map<String, Long> params = new HashMap<>();
3221                 params.put("roleId", roleId);
3222                 params.put("requestedAppId", requestedAppId);
3223                 try {
3224                         roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3225                                         params, null);
3226                 } catch (Exception e) {
3227                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3228                 }
3229                 if (roleWithApplicationRoleFucntions.size() > 0) {
3230                         List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3231                         finalGlobalrole = rolesfinalList.get(0);
3232                 } else {
3233                         List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3234                         finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3235                 }
3236                 return finalGlobalrole;
3237         }
3238
3239         private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3240                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3241                 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3242                         boolean found = false;
3243                         for (CentralV2Role cenRole : rolesfinalList) {
3244                                 if (role.getRoleId().equals(cenRole.getId())) {
3245                                         SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3246                                         CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3247                                         roleFunctions.add(cenRoleFun);
3248                                         cenRole.setRoleFunctions(roleFunctions);
3249                                         found = true;
3250                                         break;
3251                                 }
3252                         }
3253                         if (!found) {
3254                                 CentralV2Role cenrole = new CentralV2Role();
3255                                 cenrole.setName(role.getRoleName());
3256                                 cenrole.setId(role.getRoleId());
3257                                 cenrole.setActive(role.isActive());
3258                                 cenrole.setPriority(role.getPriority());
3259                                 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3260                                 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3261                                 roleFunctions.add(cenRoleFun);
3262                                 cenrole.setRoleFunctions(roleFunctions);
3263                                 rolesfinalList.add(cenrole);
3264                         }
3265                 }
3266                 return rolesfinalList;
3267         }
3268
3269         private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3270                 String instance;
3271                 String type;
3272                 String action;
3273                 CentralV2RoleFunction cenRoleFun;
3274                 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
3275                         instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3276                         type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3277                         action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3278                         cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3279                 } else{
3280                         type = getFunctionCodeType(role.getFunctionCd());
3281                         action = getFunctionCodeAction(role.getFunctionCd());
3282                         cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
3283                 }
3284                 return cenRoleFun;
3285         }
3286
3287         @SuppressWarnings("unchecked")
3288         @Override
3289         public List<EPRole> getGlobalRolesOfPortal() {
3290                 List<EPRole> globalRoles = new ArrayList<>();
3291                 try {
3292                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3293                 } catch (Exception e) {
3294                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3295                 }
3296                 return globalRoles;
3297         }
3298
3299         private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3300          return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3301                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3302                                 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3303                 
3304         }
3305         
3306         @Override
3307         public List<RoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
3308                 List<RoleFunction> addRoleFuncList = new ArrayList<>();
3309                 for(CentralV2RoleFunction cenRoleFunc : answer){
3310                         RoleFunction setRoleFunc = new RoleFunction();
3311                         setRoleFunc.setCode(cenRoleFunc.getCode());
3312                         setRoleFunc.setName(cenRoleFunc.getName());
3313                         addRoleFuncList.add(setRoleFunc);
3314                 }               
3315                 return addRoleFuncList;
3316         }
3317
3318         @Override
3319         public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3320                 CentralUser sendUserRoles = null;
3321
3322                 try {
3323                         CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3324                         sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3325                 } catch (Exception e) {
3326                         logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3327                 }
3328                 return sendUserRoles;
3329         }
3330
3331         /**
3332          * 
3333          * It returns V2 CentralUser object if user has any roles and permissions
3334          * 
3335          * @param loginId
3336          * @param uebkey
3337          * @return CentralUser object
3338          * @throws Exception
3339          */
3340         private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3341                 EPApp app;
3342                 List<EPUser> epUserList;
3343                 List<EPApp> appList = getApp(uebkey);
3344                 app = appList.get(0);
3345                 epUserList = getUser(loginId);
3346                 EPUser user = epUserList.get(0);
3347                 Set<EPUserApp> userAppSet = user.getEPUserApps();
3348                 return createEPUser(user, userAppSet, app);
3349         }
3350
3351         /**
3352          * It converts V2 CentralUser object to old version CentralUser object
3353          * 
3354          * @param cenV2User
3355          * @return EPUser object
3356          */
3357         private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3358                         Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3359                         Set<CentralUserApp> userApps = new TreeSet<>();
3360                         for(CentralV2UserApp userApp : userV2Apps){                             
3361                                 CentralApp app  = userApp.getApp();
3362                                 CentralUserApp cua = new CentralUserApp();
3363                                 cua.setUserId(null);
3364                                 cua.setApp(app);
3365                                 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3366                                 for(CentralV2RoleFunction  cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){                                      
3367                                         CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());                                                            
3368                                         cenRoleFunction.add(cenRoleFunc);
3369                                 }
3370                                 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().isActive(), userApp.getRole().getPriority(),
3371                                                 cenRoleFunction);
3372                                 cua.setRole(role);
3373                                 userApps.add(cua);
3374                         }
3375                         return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(), 
3376                                         cenV2User.getCreatedId(),cenV2User.getModifiedId(), 
3377                                         cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(), 
3378                                         cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), 
3379                                         cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
3380                                         cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(), 
3381                                         cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(), 
3382                                         cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(), 
3383                                         cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(), 
3384                                         cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(), 
3385                                         cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(), 
3386                                         cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
3387                                         cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(), 
3388                                         cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
3389                                         cenV2User.isOnline(),cenV2User.getChatId(), 
3390                                         userApps);
3391         }
3392
3393         @Override
3394         public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3395                 List<CentralRole> cenRoleList = new ArrayList<>();
3396                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3397                         for(CentralV2Role v2CenRole : v2CenRoleList){
3398                                 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
3399                                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3400                                         cenRoleFuncList.add(roleFunc);
3401                                 }
3402                                 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), cenRoleFuncList);
3403                                 cenRoleList.add(role);
3404                         }               
3405                 return cenRoleList;
3406         }
3407         
3408         @Override
3409         public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3410                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3411                 HttpEntity<String> entity = new HttpEntity<>(headers);
3412                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3413                 ResponseEntity<String> response = null;
3414                 try {
3415                         response = template
3416                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3417                                                         + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3418                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3419                                         response.getStatusCode().value());
3420                 } catch (HttpClientErrorException e) {
3421                         logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3422                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3423                         if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3424                                 throw new InvalidApplicationException("Invalid NameSpace");
3425                         else
3426                                 throw e;
3427                 }
3428                 return response;
3429         }
3430         
3431         @Override
3432         public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3433                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3434                 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3435                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3436                         cenRoleFuncList.add(roleFunc);
3437                 }
3438                 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(),
3439                                 cenRoleFuncList);
3440         }
3441
3442         @SuppressWarnings("unchecked")
3443         @Override
3444         public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3445                 EPApp app = getApp(uebkey).get(0);
3446                 final Map<String, String> params = new HashMap<>();
3447                 params.put("uebKey", app.getUebKey());
3448                 params.put("roleId", String.valueOf(roleId));
3449                 List<BulkUploadUserRoles> userRolesList = null;
3450                 Integer userRolesAdded = 0;
3451                 if (app.getCentralAuth()) {
3452                         userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3453                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3454                                 userRolesUpload.setRoleName(modifiedRoleName);
3455                                 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3456                                         addUserRoleInExternalSystem(userRolesUpload);
3457                                         userRolesAdded++;
3458                                 }
3459                         }
3460                 }
3461                 return userRolesAdded;
3462         }       
3463         
3464         @Override
3465         public String encodeFunctionCode(String funCode){
3466                 String encodedString = funCode;
3467                 List<Pattern> encodingList = new ArrayList<>();
3468                 encodingList.add(Pattern.compile("/"));
3469                 encodingList.add(Pattern.compile("-"));
3470                 for (Pattern xssInputPattern : encodingList) {
3471                         encodedString = xssInputPattern.matcher(encodedString)
3472                                         .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
3473                 }               
3474                 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
3475                 return encodedString;
3476         }
3477 }