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