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