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