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