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