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