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