diff options
39 files changed, 2300 insertions, 1578 deletions
diff --git a/LICENSE.txt b/LICENSE.txt index 9532e5b8..fd27b3ef 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,19 +1,35 @@ -/* - * ============LICENSE_START=========================================================== - * ==================================================================================== - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ==================================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================================= - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */
\ No newline at end of file +============LICENSE_START========================================== +ONAP Portal +=================================================================== +Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. +=================================================================== + +Unless otherwise specified, all software contained herein is licensed +under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Unless otherwise specified, all documentation contained herein is licensed +under the Creative Commons License, Attribution 4.0 Intl. (the "License"); +you may not use this documentation except in compliance with the License. +You may obtain a copy of the License at + + https://creativecommons.org/licenses/by/4.0/ + +Unless required by applicable law or agreed to in writing, documentation +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +============LICENSE_END============================================ + +ECOMP is a trademark and service mark of AT&T Intellectual Property. diff --git a/deliveries/docker-compose.yml b/deliveries/docker-compose.yml index 63268e0b..2b33c8ee 100644 --- a/deliveries/docker-compose.yml +++ b/deliveries/docker-compose.yml @@ -7,6 +7,9 @@ version: '2.0' services: + # Available from ONAP Nexus repository: + # docker login -u USER -p PASS nexus3.onap.org:10001 + # docker pull nexus3.onap.org:10001/onap/cli:1.1-STAGING-latest cli: image: onap/cli:${PORTAL_TAG} environment: @@ -46,7 +49,7 @@ services: command: - /wait-for.sh - -t - - "60" + - "180" - portal-db:3306 - -- - /start-wms-cmd.sh @@ -86,7 +89,7 @@ services: command: - /wait-for.sh - -t - - "60" + - "180" - portal-db:3306 - -- - /start-apps-cmd.sh diff --git a/ecomp-portal-BE-common/pom.xml b/ecomp-portal-BE-common/pom.xml index af828cf2..79968b3a 100644 --- a/ecomp-portal-BE-common/pom.xml +++ b/ecomp-portal-BE-common/pom.xml @@ -12,27 +12,31 @@ <hibernate.version>4.3.11.Final</hibernate.version> <eelf.version>1.0.0</eelf.version> <fasterxml.version>2.7.4</fasterxml.version> - <epsdk.version>1.3.0-SNAPSHOT</epsdk.version> + <epsdk.version>1.3.0</epsdk.version> <encoding>UTF-8</encoding> <!-- Tests usually require some setup that maven cannot do, so skip. --> <skipTests>true</skipTests> <nexusproxy>https://nexus.onap.org</nexusproxy> <snapshotNexusPath>/content/repositories/snapshots/</snapshotNexusPath> + <stagingNexusPath>content/repositories/staging/</stagingNexusPath> <releaseNexusPath>/content/repositories/releases/</releaseNexusPath> </properties> <repositories> <repository> - <!-- Releases repository has ECOMP release artifacts --> - <id>ecomp-releases</id> - <name>OpenECOMP - Release Repository</name> - <url>${nexusproxy}/${releaseNexusPath}</url> + <id>onap-releases</id> + <name>ONAP - Release Repository</name> + <url>${nexusproxy}/${releaseNexusPath}</url> </repository> <repository> - <!-- Snapshots repository has ECOMP snapshot artifacts --> - <id>ecomp-snapshots</id> - <name>OpenECOMP - Snapshot Repository</name> - <url>${nexusproxy}/${snapshotNexusPath}</url> + <id>onap-staging</id> + <name>ONAP - Staging Repository</name> + <url>${nexusproxy}/${stagingNexusPath}</url> + </repository> + <repository> + <id>onap-snapshots</id> + <name>ONAP - Snapshot Repository</name> + <url>${nexusproxy}/${snapshotNexusPath}</url> </repository> </repositories> diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java index 8d6b8e63..14ba94f2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java @@ -36,6 +36,8 @@ import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice; import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; import org.openecomp.portalapp.util.EPUserUtils; @RestController @@ -83,7 +85,7 @@ public class AuditLogController extends EPRestrictedBaseController { * valid */ if (comment != null && !comment.equals("") && !comment.equals("undefined")) - auditLog.setComments(comment); + auditLog.setComments(EcompPortalUtils.truncateString(comment, PortalConstants.AUDIT_LOG_COMMENT_SIZE)); if (affectedAppId != null && !affectedAppId.equals("") && !affectedAppId.equals("undefined")) auditLog.setAffectedRecordId(affectedAppId); long userId = EPUserUtils.getUserId(request); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java index 81a61d57..1c22576d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java @@ -44,6 +44,7 @@ import org.openecomp.portalapp.portal.transport.CommonWidget; import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; import org.openecomp.portalapp.util.EPUserUtils; import org.openecomp.portalsdk.core.domain.AuditLog; import org.openecomp.portalsdk.core.domain.support.CollaborateList; @@ -244,7 +245,7 @@ public class DashboardController extends EPRestrictedBaseController { AuditLog auditLog = new AuditLog(); auditLog.setUserId(user.getId()); auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH); - auditLog.setComments(searchString); + auditLog.setComments(EcompPortalUtils.truncateString(searchString, PortalConstants.AUDIT_LOG_COMMENT_SIZE)); MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); auditService.logActivity(auditLog, null); MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java index 43e07af3..fabf5e10 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java @@ -9,14 +9,25 @@ import javax.servlet.http.HttpServletResponse; import org.openecomp.portalapp.portal.domain.CentralRoleFunction; import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EcompAuditLog; import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalapp.portal.service.ExternalAccessRolesService; import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.domain.AuditLog; import org.openecomp.portalsdk.core.domain.Role; import org.openecomp.portalsdk.core.domain.RoleFunction; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.AuditService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.bind.annotation.PathVariable; @@ -37,6 +48,11 @@ import io.swagger.annotations.ApiOperation; @EPAuditLog public class ExternalAccessRolesController implements BasicAuthenticationController { + private static final String LOGIN_ID = "LoginId"; + + @Autowired + private AuditService auditService; + private static final String UEBKEY = "uebkey"; private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesController.class); @@ -51,7 +67,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl String answer = null; try { - answer = externalAccessRolesService.getUser(loginId, request.getHeader(UEBKEY)); + answer = externalAccessRolesService.getUserWithRoles(loginId, request.getHeader(UEBKEY)); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getUser failed", e); } @@ -66,7 +82,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl List<EPApp> applicationList=new ArrayList<>(); applicationList = externalAccessRolesService.getApp(request.getHeader(UEBKEY)); EPApp app = applicationList.get(0); - externalAccessRolesService.SyncApplicationRolesWithEcompDB(app); + externalAccessRolesService.syncApplicationRolesWithEcompDB(app); List<CentralRole> answer = null; try { answer = externalAccessRolesService.getRolesForApp(request.getHeader(UEBKEY)); @@ -141,7 +157,38 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl String data = roleFunc; CentralRoleFunction availableRoleFunction = mapper.readValue(data, CentralRoleFunction.class); availableRoleFunction.setAppId(appId); - externalAccessRolesService.saveCentralRoleFunction(availableRoleFunction, requestedApp); + boolean saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(availableRoleFunction, requestedApp); + if(saveOrUpdateResponse){ + EPUser user = externalAccessRolesService.getUser(request.getHeader(LOGIN_ID)).get(0); + EPApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0); + CentralRoleFunction function = externalAccessRolesService.getRoleFunction(availableRoleFunction.getCode(), request.getHeader(UEBKEY)); + String activityCode = (function.getCode() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION: EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION; + logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}", + app.getId(), availableRoleFunction.getCode()); + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(activityCode); + auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"+app.getId()+" and function:'"+availableRoleFunction.getCode()+"'", PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditLog.setAffectedRecordId(user.getOrgUserId()); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.saveRoleFunction", + activityCode, String.valueOf(user.getId()), + user.getOrgUserId(), availableRoleFunction.getCode())); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed"); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to saveRoleFunction for '"+availableRoleFunction.getCode()+"'", "Failed"); + } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e); return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); @@ -153,13 +200,42 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @RequestMapping(value = { "/roleFunction/{code}" }, method = RequestMethod.DELETE, produces = "application/json") public PortalRestResponse<String> deleteRoleFunction(HttpServletRequest request, HttpServletResponse response, @PathVariable("code") String code) throws Exception { try { - externalAccessRolesService.deleteCentralRoleFunction(code, request.getHeader(UEBKEY)); + EPUser user = externalAccessRolesService.getUser(request.getHeader(LOGIN_ID)).get(0); + EPApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0); + boolean getDelFuncResponse = externalAccessRolesService.deleteCentralRoleFunction(code, app); + if(getDelFuncResponse){ + logger.info(EELFLoggerDelegate.applicationLogger, "deleteRoleFunction: succeeded for app {}, role {}", + app.getId(), code); + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION); + auditLog.setComments(EcompPortalUtils.truncateString("Deleted function for app:"+app.getId()+" and function code:'"+code+"'", PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditLog.setAffectedRecordId(user.getOrgUserId()); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.deleteRoleFunction", + EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION, String.valueOf(user.getId()), + user.getOrgUserId(), code)); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed"); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to deleteRoleFunction for '"+code+"'", "Failed"); + } } catch (HttpClientErrorException e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed", e); - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to deleteRoleFunction", "Failed"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to deleteRoleFunction for '"+code+"'", "Failed"); } - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully Deleted", "Success"); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully Deleted", "Success"); } @@ -168,7 +244,36 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl public PortalRestResponse<String> saveRole(HttpServletRequest request, HttpServletResponse response, @RequestBody Role role) throws Exception { try { - externalAccessRolesService.saveRoleForApplication(role,request.getHeader(UEBKEY)); + EPUser user = externalAccessRolesService.getUser(request.getHeader(LOGIN_ID)).get(0); + EPApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0); + boolean getAddResponse = externalAccessRolesService.saveRoleForApplication(role, request.getHeader(UEBKEY)); + if (getAddResponse) { + String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE + : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION; + logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}", + app.getId(), role.getName()); + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(activityCode); + auditLog.setComments(EcompPortalUtils.truncateString("saveRole role for app:" + app.getId() + " and role:'" + role.getName()+"'", PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditLog.setAffectedRecordId(user.getOrgUserId()); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.saveRole", activityCode, + String.valueOf(user.getId()), user.getOrgUserId(), role.getName())); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } else { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to saveRole for '"+role.getName()+"'", "Failed"); + + } } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e); @@ -182,7 +287,36 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl public PortalRestResponse<String> deleteRole(HttpServletRequest request, HttpServletResponse response, @PathVariable String code) throws Exception { try { - externalAccessRolesService.deleteRoleForApplication(code, request.getHeader(UEBKEY)); + boolean deleteResponse = externalAccessRolesService.deleteRoleForApplication(code, request.getHeader(UEBKEY)); + if(deleteResponse){ + EPUser user = externalAccessRolesService.getUser(request.getHeader(LOGIN_ID)).get(0); + EPApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0); + logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}", + app.getId(), code); + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE); + auditLog.setComments(EcompPortalUtils.truncateString("Deleted role for app:"+app.getId()+" and role:'"+code+"'", PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditLog.setAffectedRecordId(user.getOrgUserId()); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.deleteRole", + EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE, String.valueOf(user.getId()), + user.getOrgUserId(), code)); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed"); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to deleteRole for '"+code+"'", "Failed"); + } } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e); @@ -208,15 +342,23 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @ApiOperation(value = "deletes user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json") @RequestMapping(value = { "/deleteDependcyRoleRecord/{roleId}" }, method = RequestMethod.DELETE, produces = "application/json") - public PortalRestResponse<String> deleteDependcyRoleRecord(HttpServletRequest request, HttpServletResponse response, @PathVariable("roleId") Long roleId) throws Exception { + public PortalRestResponse<String> deleteDependencyRoleRecord(HttpServletRequest request, HttpServletResponse response, + @PathVariable("roleId") Long roleId) throws Exception { try { - externalAccessRolesService.deleteDependcyRoleRecord(roleId,request.getHeader(UEBKEY), request.getHeader("LoginId")); + boolean deleteResponse = externalAccessRolesService.deleteDependencyRoleRecord(roleId, + request.getHeader(UEBKEY), request.getHeader(LOGIN_ID)); + if (!deleteResponse) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to deleteDependencyRoleRecord", + "Failed"); + } } catch (HttpClientErrorException e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", e); - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to deleteDependcyRoleRecord", "Failed"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to deleteDependencyRoleRecord", + "Failed"); } - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully Deleted", "Success"); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully Deleted", "Success"); } @ApiOperation(value = "Bulk upload functions for an application.", response = PortalRestResponse.class, responseContainer = "Json") diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java index b98a7cb4..7bb6c45d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java @@ -111,8 +111,11 @@ public class PortalAdminController extends EPRestrictedBaseController { auditLog.setUserId(user.getId()); auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN); auditLog.setAffectedRecordId(userId); - auditService.logActivity(auditLog, null); - + try { + auditService.logActivity(auditLog, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "createPortalAdmin: failed for save audit log", e); + } MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); EcompPortalUtils.calculateDateTimeDifferenceForLog( @@ -164,7 +167,7 @@ public class PortalAdminController extends EPRestrictedBaseController { auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN); auditLog.setAffectedRecordId(sbcid); auditService.logActivity(auditLog, null); - + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); EcompPortalUtils.calculateDateTimeDifferenceForLog( diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java index eefd5004..02f237d7 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java @@ -175,7 +175,7 @@ public class RoleManageController extends EPRestrictedBaseController { public void syncRoles(EPApp app) { try { - externalAccessRolesService.SyncApplicationRolesWithEcompDB(app); + externalAccessRolesService.syncApplicationRolesWithEcompDB(app); } catch (Exception e) { logger.error(EELFLoggerDelegate.debugLogger, "failed syncRoles"); } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java index 102f7709..222f4502 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java @@ -180,15 +180,16 @@ public class TicketEventController implements BasicAuthenticationController { JsonNode application = ticketEventNotif.get("application"); JsonNode event = ticketEventNotif.get("event"); JsonNode header = event.get("header"); + JsonNode eventSource=header.get("eventSource"); JsonNode body = event.get("body"); JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo"); JsonNode userList = SubscriberInfo.get("UserList"); - if (application == null) + if (application == null||application.asText().length()==0||application.asText().equalsIgnoreCase("null")) return "Application is mandatory"; if (body == null) return "body is mandatory"; - if (header.get("eventSource") == null) + if (eventSource == null||eventSource.asText().trim().length()==0||eventSource.asText().equalsIgnoreCase("null")) return "Message Source is mandatory"; if (userList == null) return "At least one user Id is mandatory"; diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java index 7bcd5845..4bb447d1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java @@ -52,6 +52,7 @@ import org.openecomp.portalapp.portal.transport.RoleInAppForUser; import org.openecomp.portalapp.portal.transport.UserApplicationRoles; import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; import org.openecomp.portalapp.util.EPUserUtils; import org.openecomp.portalsdk.core.domain.AuditLog; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -213,7 +214,7 @@ public class UserRolesController extends EPRestrictedBaseController { auditLog.setUserId(user.getId()); auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN); auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId); - auditLog.setComments(newAppRoles.toString()); + auditLog.setComments(EcompPortalUtils.truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE)); auditService.logActivity(auditLog, null); MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); @@ -344,13 +345,15 @@ public class UserRolesController extends EPRestrictedBaseController { logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.appId, newAppRolesForUser.orgUserId); + + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); AuditLog auditLog = new AuditLog(); auditLog.setUserId(user.getId()); auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER); auditLog.setAffectedRecordId(newAppRolesForUser.orgUserId); - auditLog.setComments(sbUserApps.toString()); - MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE)); auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); EcompPortalUtils.calculateDateTimeDifferenceForLog( MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAuditLog.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAuditLog.java index 3d53c8d3..63ac2c7e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAuditLog.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAuditLog.java @@ -51,7 +51,12 @@ public class EcompAuditLog extends AuditLog { public static final String CD_ACTIVITY_UPDATE_USER = "uu "; public static final String CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN = "uaa "; public static final String CD_ACTIVITY_STORE_ANALYTICS = "store_analytics"; - + public static final String CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE = "eaar"; + public static final String CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION = "eaaf"; + public static final String CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION = "eauf"; + public static final String CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION = "eaurf"; + public static final String CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE = "eadr"; + public static final String CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION = "eadf"; /** * Creates a new object with the created field set to the current date-time. */ diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java index 62519530..eaac6edf 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java @@ -186,7 +186,16 @@ public enum EPAppMessagesEnum { InternalUnexpectedFatal(EPErrorCodesEnum.INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, "ERR999F", "Unexpected error", "Details: {0}.", "Please check logs for more information."), - + + ExternalAuthAccessConnectionError(EPErrorCodesEnum.EXTERNALAUTHACCESS_CONNECTIONERROR, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR220E", "AAF Connection problem", "Details: {0}.", "Please check logs for more information."), + + ExternalAuthAccessAuthenticationError(EPErrorCodesEnum.EXTERNALAUTHACCESS_AUTHENTICATIONERROR, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR120E", "AAF authentication problem", "Details: {0}.", "Please check logs for more information."), + + ExternalAuthAccessGeneralError(EPErrorCodesEnum.EXTERNALAUTHACCESS_GENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR520E", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + ; ErrorTypeEnum eType; diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java index 99a6c34a..ca4cdec1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java @@ -82,6 +82,10 @@ public enum EPErrorCodesEnum implements EELFResolvableErrorEnum { INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, + + EXTERNALAUTHACCESS_CONNECTIONERROR, + EXTERNALAUTHACCESS_AUTHENTICATIONERROR, + EXTERNALAUTHACCESS_GENERALERROR, ; /** diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java index ebda67e6..2c6b3300 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java @@ -29,6 +29,7 @@ import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.openecomp.portalsdk.core.web.support.UserUtils; import org.slf4j.MDC; +import org.springframework.http.HttpStatus; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; @@ -282,4 +283,15 @@ public class EPLogUtil { return auditLogStoreAnalyticsMsg.toString(); } + public static void logExternalAuthAccessAlarm(EELFLoggerDelegate logger, HttpStatus res) { + if (res.equals(HttpStatus.UNAUTHORIZED) || res.equals(HttpStatus.FORBIDDEN)) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.ExternalAuthAccessAuthenticationError); + } else if (res.equals(HttpStatus.NOT_FOUND) || res.equals(HttpStatus.NOT_ACCEPTABLE) + || res.equals(HttpStatus.CONFLICT) || res.equals(HttpStatus.BAD_REQUEST)) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.ExternalAuthAccessConnectionError); + } else if (!res.equals(HttpStatus.ACCEPTED) && !res.equals(HttpStatus.OK)) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.ExternalAuthAccessGeneralError); + } + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java index e57d4fa5..34088a22 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java @@ -6,6 +6,7 @@ import org.hibernate.Session; import org.openecomp.portalapp.portal.domain.CentralRoleFunction; import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.transport.CentralRole; import org.openecomp.portalsdk.core.domain.Role; import org.openecomp.portalsdk.core.domain.RoleFunction; @@ -13,17 +14,16 @@ import org.openecomp.portalsdk.core.domain.RoleFunction; public interface ExternalAccessRolesService { /** - * It gets all application roles + * It gets list of application roles * * @param appId - * @param extRequestValue * @return List * @throws Exception */ - public List<EPRole> getAppRoles(Long appId, Boolean extRequestValue) throws Exception; + public List<EPRole> getAppRoles(Long appId) throws Exception; /** - * It returns application details + * It returns single app record * * @param uebkey * @return List @@ -40,17 +40,16 @@ public interface ExternalAccessRolesService { * @throws Exception */ public boolean addRole(Role addRoles, String uebkey) throws Exception; - + /** - * Updates role in the external access system otherwise throws exception + * It returns complete user information * - * @param updateRole - * @param uebkey - * @return boolean + * @param loginId + * @return EPUser object * @throws Exception */ - void updateRole(Role updateRole, EPApp app) throws Exception; - + List<EPUser> getUser(String loginId) throws Exception; + /** * It returns complete user information including application roles permissions * @@ -59,7 +58,7 @@ public interface ExternalAccessRolesService { * @return String * @throws Exception */ - String getUser(String loginId, String uebkey) throws Exception; + String getUserWithRoles(String loginId, String uebkey) throws Exception; /** * It returns list of all role functions @@ -94,17 +93,18 @@ public interface ExternalAccessRolesService { * * @param domainCentralRoleFunction * @param requestedApp + * @return true else false * @throws Exception */ - public void saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp requestedApp) throws Exception; + public boolean saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp requestedApp) throws Exception; /** * It deletes role function in the DB * * @param code - * @param string + * @param app */ - public void deleteCentralRoleFunction(String code, String string); + public boolean deleteCentralRoleFunction(String code, EPApp app); /** * It gets all roles the applications @@ -122,16 +122,17 @@ public interface ExternalAccessRolesService { * @param uebkey * @throws Exception */ - void saveRoleForApplication(Role saveRole, String uebkey) throws Exception; + boolean saveRoleForApplication(Role saveRole, String uebkey) throws Exception; /** * It deletes role in the DB * * @param code * @param uebkey + * @return true else false * @throws Exception */ - void deleteRoleForApplication(String code, String uebkey) throws Exception; + boolean deleteRoleForApplication(String code, String uebkey) throws Exception; /** * It gets all active roles for single application @@ -147,10 +148,10 @@ public interface ExternalAccessRolesService { * @param roleId * @param uebkey * @param LoginId - * @return + * @return true else false * @throws Exception */ - public void deleteDependcyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception; + public boolean deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception; /** * It sync new functions codes and names from and updates role functions from external access system @@ -160,30 +161,90 @@ public interface ExternalAccessRolesService { */ public void syncRoleFunctionFromExternalAccessSystem(EPApp app) throws Exception; + /** + * It uploads portal functions into external auth system + * @param uebkey + * @return + * @throws Exception + */ public Integer bulkUploadFunctions(String uebkey) throws Exception; + /** + * It uploads portal roles into external auth system + * @param uebkey + * @return + * @throws Exception + */ public Integer bulkUploadRoles(String uebkey) throws Exception; - public void bulkUploadPartnerFunctions(String header, List<RoleFunction> upload) throws Exception; + /** + * It uploads partner application role functions into external auth system + * + * @param uebkey + * @param upload + * @throws Exception + */ + public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> upload) throws Exception; - public void bulkUploadPartnerRoles(String header, List<Role> upload) throws Exception; + /** + * It uploads partner application role functions into external auth system + * + * @param uebkey + * @param upload + * @throws Exception + */ + public void bulkUploadPartnerRoles(String uebkey, List<Role> upload) throws Exception; + /** + * It returns total no. of portal application role functions records added in external auth system + * @param uebkey + * @return + * @throws Exception + */ Integer bulkUploadRolesFunctions(String uebkey) throws Exception; /** - * SyncApplicationRolesWithEcompDB sync the roles and rolefunctions to the ecomp DB from AAF + * It syncs the roles and rolefunctions to the ecomp DB from AAF * @param app * @throws Exception */ + void syncApplicationRolesWithEcompDB(EPApp app) throws Exception; - void SyncApplicationRolesWithEcompDB(EPApp app) throws Exception; - + /** + * It uploads list of user roles of the application into external auth system + * + * @param uebkey + * @return + * @throws Exception + */ public Integer bulkUploadUserRoles(String uebkey) throws Exception; + /** + * It Uploads partner application role functions into external auth system + * + * @param uebkey + * @param roleList + * @throws Exception + */ void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception; - public void deleteRoleDependeciesRecord(Session localSession, Long roleId) throws Exception; + /** + * it deletes all dependency role records + * + * @param localSession + * @param roleId + * @param appId + * @throws Exception + */ + public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId) throws Exception; + /** + * It returns list of applications functions along with functions associated with global role + * + * @param uebkey + * @return + * @throws Exception + */ List<String> getMenuFunctionsList(String uebkey) throws Exception; diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java index 17d9ceb0..95e5ddce 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java @@ -3,6 +3,7 @@ package org.openecomp.portalapp.portal.service; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -23,7 +24,9 @@ import org.openecomp.portalapp.portal.domain.EPRole; import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.domain.EPUserApp; import org.openecomp.portalapp.portal.domain.ExternalRoleDetails; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction; import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles; import org.openecomp.portalapp.portal.transport.CentralApp; @@ -52,6 +55,7 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonProcessingException; @@ -62,32 +66,62 @@ import com.fasterxml.jackson.databind.type.TypeFactory; @Service("externalAccessRolesService") @EnableAspectJAutoProxy @EPMetricsLog +@EPAuditLog public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService { + private static final String IS_NULL_STRING = "null"; + + private static final String EXTERNAL_AUTH_PERMS = "perms"; + + private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description"; + + private static final String WHERE_APP_ID_EQUALS = " where app_id = "; + + private static final String IS_EMPTY_JSON_STRING = "{}"; + + private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system"; + + private static final String WHERE_ROLE_ID_EQUALS = " where role_id = "; + + private static final String APP_ROLE_ID = "appRoleId"; + + private static final String APP_ID = "appId"; + + private static final String PRIORITY = "priority"; + + private static final String ACTIVE = "active"; + + private static final String ROLE_NAME = "name"; + + private static final String ID = "id"; + + private static final String WHERE_ROLE_NAME_EQUALS = " where role_name = '"; + + private static final String APP_ID_EQUALS = " app_id = "; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class); @Autowired private DataAccessService dataAccessService; - + @Autowired private SessionFactory sessionFactory; - RestTemplate template = new RestTemplate(); @SuppressWarnings("unchecked") - public List<EPRole> getAppRoles(Long appId, Boolean extRequestValue) throws Exception { + public List<EPRole> getAppRoles(Long appId) throws Exception { List<EPRole> applicationRoles = null; String filter = null; try { if (appId == 1) { filter = " where app_id is null"; } else { - filter = " where app_id = " + appId; + filter = WHERE_APP_ID_EQUALS + appId; } applicationRoles = dataAccessService.getList(EPRole.class, filter, null, null); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles is failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e); throw new Exception(e.getMessage()); } return applicationRoles; @@ -99,27 +133,35 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic List<EPApp> app = null; try { app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null); + if(!app.get(0).getEnabled()){ + throw new Exception("Application:"+app.get(0).getName()+" is Unavailable"); + } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getApp is failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e); throw new Exception(e.getMessage()); } return app; } - public String getSingleAppRole(String addRole, EPApp app) throws Exception { - String response = ""; + /** + * It returns single application role from external auth system + * @param addRole + * @param app + * @return JSON string which contains application role details + * @throws Exception + */ + private String getSingleAppRole(String addRole, EPApp app) throws Exception { HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - response = template + logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system"); + ResponseEntity<String> response = template .exchange( SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/" + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"), - HttpMethod.GET, entity, String.class) - .getBody(); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); - - return response; + HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ", response.getStatusCode().value()); + return response.getBody(); } @Override @@ -128,43 +170,52 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ResponseEntity<String> addResponse = null; HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); EPApp app = getApp(uebkey).get(0); - String newRole = createNewRoleInExternalSystem(addRole, app); + String newRole = updateExistingRoleInExternalSystem(addRole, app); HttpEntity<String> entity = new HttpEntity<>(newRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system"); addResponse = template.exchange( SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", HttpMethod.POST, entity, String.class); if (addResponse.getStatusCode().value() == 201) { response = true; - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system and response code: {} ", addResponse.getStatusCode().value()); } if (addResponse.getStatusCode().value() == 406) { - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system but something went wrong!"); - throw new Exception("Failed to create role"); + logger.error(EELFLoggerDelegate.errorLogger, + "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value()); } return response; } - @Override - public void updateRole(Role addRole, EPApp app) throws Exception { - boolean addResponse = updateRoleInExternalSystem(addRole, app); - if (!addResponse) { - throw new Exception("Failed to update a role"); - } - } - + /** + * + * It deletes record in external auth system + * + * @param delRole + * @return JSON String which has status code and response body + * @throws Exception + */ private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception { ResponseEntity<String> delResponse = null; HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); HttpEntity<String> entity = new HttpEntity<>(delRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); delResponse = template.exchange( SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true", HttpMethod.DELETE, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system and status code: {} ", delResponse.getStatusCode().value()); return delResponse; } + /** + * It updates role in external auth system + * + * @param updateExtRole + * @param app + * @return true if success else false + * @throws Exception + * If updateRoleInExternalSystem fails we catch it in logger for detail message + */ @SuppressWarnings("unchecked") private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app) throws Exception { boolean response = false; @@ -174,75 +225,85 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ExternalAccessRolePerms extRolePerms = null; ExternalAccessPerms extPerms = null; List<EPRole> epRoleList = null; - epRoleList = dataAccessService.getList(EPRole.class, - " where role_id = " + updateExtRole.getId(), null, null); + epRoleList = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + updateExtRole.getId(), null, null); String appRole = getSingleAppRole(epRoleList.get(0).getName(), app); - if (!appRole.equals("{}")) { + if (!appRole.equals(IS_EMPTY_JSON_STRING)) { JSONObject jsonObj = new JSONObject(appRole); JSONArray extRole = jsonObj.getJSONArray("role"); - if (!extRole.getJSONObject(0).has("description")) { - String roleName = extRole.getJSONObject(0).getString("name"); - String delRoleKey = "{\"name\":\"" + roleName + "\"}"; - deleteResponse = deleteRoleInExternalSystem(delRoleKey); + if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) { + String roleName = extRole.getJSONObject(0).getString(ROLE_NAME); + Map<String, String> delRoleKeyMapper = new HashMap<>(); + delRoleKeyMapper.put(ROLE_NAME, roleName); + String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper); + deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue); if (deleteResponse.getStatusCode().value() != 200) { - throw new Exception("Failed to delete role in external access system!"); + throw new Exception(deleteResponse.getBody()); } addRole(updateExtRole, app.getUebKey()); } else { - String desc = extRole.getJSONObject(0).getString("description"); - String name = extRole.getJSONObject(0).getString("name"); + String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); + String name = extRole.getJSONObject(0).getString(ROLE_NAME); List<ExternalAccessPerms> list = null; - if (extRole.getJSONObject(0).has("perms")) { - JSONArray perms = extRole.getJSONObject(0).getJSONArray("perms"); - ObjectMapper permsMapper = new ObjectMapper(); - list = permsMapper.readValue(perms.toString(), TypeFactory.defaultInstance() + if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) { + JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS); + list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance() .constructCollectionType(List.class, ExternalAccessPerms.class)); } - ObjectMapper roleMapper = new ObjectMapper(); - ExternalRoleDescription sysRoleList = roleMapper.readValue(desc, ExternalRoleDescription.class); + ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class); // If role name or role functions are updated then delete record in External System and add new record to avoid conflicts Boolean existingRoleActive; - boolean res; + boolean isActiveValueChanged; // check role active status existingRoleActive = new Boolean(sysRoleList.getActive()); - res = existingRoleActive.equals(updateExtRole.getActive()); + isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive()); if (!sysRoleList.getName().equals(updateExtRole.getName())) { - String deleteRoleKey = "{\"name\":\"" + name + "\"}"; - deleteResponse = deleteRoleInExternalSystem(deleteRoleKey); + Map<String, String> delRoleKeyMapper = new HashMap<>(); + delRoleKeyMapper.put(ROLE_NAME, name); + String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper); + deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue); if (deleteResponse.getStatusCode().value() != 200) { - throw new Exception("Failed to delete role in external access system!"); + logger.error(EELFLoggerDelegate.errorLogger, "updateRoleInExternalSystem: Failed to delete role in external system due to {} ", deleteResponse.getBody()); + throw new Exception(deleteResponse.getBody()); } - response = addRole(updateExtRole, app.getUebKey()); - ObjectMapper addPermsMapper = new ObjectMapper(); - response = addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app); + addRole(updateExtRole, app.getUebKey()); + addRoleFunctionsInExternalSystem(updateExtRole, mapper, app); } ExternalAccessRole updateRole = new ExternalAccessRole(); - if (!res || !sysRoleList.getPriority().equals(String.valueOf(updateExtRole.getPriority())) || - sysRoleList.getId().equals("null")) { + if (!isActiveValueChanged + || !sysRoleList.getPriority().equals(String.valueOf(updateExtRole.getPriority())) + || sysRoleList.getId().equals(IS_NULL_STRING) + || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) { String updateDesc = ""; + String appId = (app.getId().equals(PortalConstants.PORTAL_APP_ID)) ? " app_id is null" + : APP_ID_EQUALS + app.getId(); List<EPRole> getRole = dataAccessService.getList(EPRole.class, - " where role_name = '" + updateExtRole.getName() + "'", null, null); + WHERE_ROLE_NAME_EQUALS + updateExtRole.getName() + "' and " + appId, null, null); + Map<String, Object> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>(); + extSystemUpdateRoleJsonMapper.put(ID, getRole.get(0).getId()); + extSystemUpdateRoleJsonMapper.put(ROLE_NAME, updateExtRole.getName()); + extSystemUpdateRoleJsonMapper.put(ACTIVE, updateExtRole.getActive()); + extSystemUpdateRoleJsonMapper.put(PRIORITY, updateExtRole.getPriority()); if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - updateDesc = "{\"id\":\"" + getRole.get(0).getId() + "\",\"name\":\"" + updateExtRole.getName() - + "\",\"active\":\"" + updateExtRole.getActive() + "\",\"priority\":\"" - + updateExtRole.getPriority() + "\",\"appId\":\"null\",\"appRoleId\":\"null\"}"; - + extSystemUpdateRoleJsonMapper.put(APP_ID, null); + extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, null); } else { - updateDesc = "{\"id\":\"" + getRole.get(0).getId() + "\",\"name\":\"" + updateExtRole.getName() - + "\",\"active\":\"" + updateExtRole.getActive() + "\",\"priority\":\"" - + updateExtRole.getPriority() + "\",\"appId\":\"" + app.getId() + "\",\"appRoleId\":\"" - + getRole.get(0).getAppRoleId() + "\"}"; + extSystemUpdateRoleJsonMapper.put(APP_ID, app.getId()); + extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, getRole.get(0).getAppRoleId()); } + updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper); updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); updateRole.setDescription(updateDesc); String updateRoleDesc = mapper.writeValueAsString(updateRole); HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - template.exchange( + logger.debug(EELFLoggerDelegate.debugLogger, + "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> updatePermsResponse = template.exchange( SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", HttpMethod.PUT, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateRoleInExternalSystem: Finished updating in External Auth system and status code: {} ", + updatePermsResponse.getStatusCode().value()); } List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole); Map<String, RoleFunction> updateRoleFunc = new HashMap<>(); @@ -251,17 +312,16 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>(); // Update permissions in the ExternalAccess System - ObjectMapper permMapper = new ObjectMapper(); if (list != null) { for (ExternalAccessPerms perm : list) { if (!updateRoleFunc.containsKey(perm.getInstance())) { - removePermForRole(perm, permMapper, name, headers); + removePermForRole(perm, mapper, name, headers); } extRolePermMap.put(perm.getInstance(), perm); } } response = true; - if (!roleFunctionListNew.isEmpty() || roleFunctionListNew.size() > 0) { + if (!roleFunctionListNew.isEmpty()) { for (RoleFunction roleFunc : roleFunctionListNew) { if (!extRolePermMap.containsKey(roleFunc.getCode())) { String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url"; @@ -271,7 +331,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); String updateRolePerms = mapper.writeValueAsString(extRolePerms); HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); ResponseEntity<String> addResponse = template.exchange( SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", @@ -279,29 +339,41 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (addResponse.getStatusCode().value() != 201) { response = false; logger.debug(EELFLoggerDelegate.debugLogger, - "Connected to External Access system but something went wrong! due to {} and statuscode: {}", addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}", + addResponse.getStatusCode().getReasonPhrase(), + addResponse.getStatusCode().value()); } else { response = true; - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value()); } } } } } } else { - // It seems like role exists in local DB but not in External Access system + // It seems like role exists in local DB but not in External Access system addRole(updateExtRole, app.getUebKey()); List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole); response = true; - if (!roleFunctionListUpdate.isEmpty() || roleFunctionListUpdate.size() > 0) { - ObjectMapper addPermsMapper = new ObjectMapper(); - addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app); + if (!roleFunctionListUpdate.isEmpty()) { + addRoleFunctionsInExternalSystem(updateExtRole, mapper, app); } } return response; } - private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app) throws Exception { + /** + * + * It adds functions to the role in external auth system + * + * @param updateExtRole + * @param addPermsMapper + * @param app + * @return true if success else false + * @throws Exception + */ + private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app) + throws Exception { boolean response = false; ExternalAccessRolePerms extAddRolePerms = null; ExternalAccessPerms extAddPerms = null; @@ -309,31 +381,37 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); for (RoleFunction roleFunc : roleFunctionListAdd) { String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url"; - extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), - "*"); + extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), "*"); extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms); HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); ResponseEntity<String> addResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role/perm", + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", HttpMethod.POST, entity, String.class); if (addResponse.getStatusCode().value() != 201) { response = false; logger.debug(EELFLoggerDelegate.debugLogger, - "Connected to External Access system but something went wrong! due to {} and statuscode: {}", addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}", + addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); } else { response = true; - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value()); } } return response; } + /** + * + * It converts list of functions in updateExtRole parameter to the RoleFunction object + * + * @param updateExtRole + * @return list of functions + */ @SuppressWarnings("unchecked") - private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole){ + private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) { Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions(); List<RoleFunction> roleFunctionList = new ArrayList<>(); ObjectMapper roleFuncMapper = new ObjectMapper(); @@ -345,20 +423,41 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } return roleFunctionList.stream().distinct().collect(Collectors.toList()); } - - private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper,String name, HttpHeaders headers) throws Exception { + + /** + * It delete permissions/functions in the external auth system + * + * @param perm + * @param permMapper + * @param name + * @param headers + * @throws Exception + */ + private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers) + throws Exception { ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name); String permDetails = permMapper.writeValueAsString(extAccessRolePerms); HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - ResponseEntity<String> deletePermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role/"+name+"/perm", HttpMethod.DELETE, deleteEntity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> deletePermResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/" + + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class); if (deletePermResponse.getStatusCode().value() != 200) { - throw new Exception("Failed to delete role function"); + throw new Exception(deletePermResponse.getBody()); } - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system and status code: {}", + deletePermResponse.getStatusCode().value()); } + /** + * It will create new role in the External Auth System + * + * @param newRole + * @param app + * @return true if successfully added in the system else false + * @throws Exception + * If fails to add role in the system + */ private boolean addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception { boolean response = false; HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); @@ -366,52 +465,76 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic String addNewRole = ""; ExternalAccessRole extRole = new ExternalAccessRole(); String addDesc = null; - addDesc = "{\"id\":\"" + newRole.get(0).getId() + "\",\"name\":\"" + newRole.get(0).getName() + "\",\"active\":\"" - + newRole.get(0).getActive() + "\",\"priority\":\"" +newRole.get(0).getPriority() + "\",\"appId\":\"" - + newRole.get(0).getAppId() + "\",\"appRoleId\":\"" + newRole.get(0).getAppRoleId() + "\"}"; - + Map<String, Object> extSystemJsonMapper = new LinkedHashMap<>(); + extSystemJsonMapper.put(ID, newRole.get(0).getId()); + extSystemJsonMapper.put(ROLE_NAME, newRole.get(0).getName()); + extSystemJsonMapper.put(ACTIVE, newRole.get(0).getActive()); + extSystemJsonMapper.put(PRIORITY, newRole.get(0).getPriority()); + extSystemJsonMapper.put(APP_ID, newRole.get(0).getAppId()); + extSystemJsonMapper.put(APP_ROLE_ID, newRole.get(0).getAppRoleId()); + addDesc = mapper.writeValueAsString(extSystemJsonMapper); extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_")); extRole.setDescription(addDesc); addNewRole = mapper.writeValueAsString(extRole); HttpEntity<String> deleteEntity = new HttpEntity<>(addNewRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role", HttpMethod.POST, deleteEntity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> addNewRoleInExternalSystem = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, deleteEntity, String.class); if (addNewRoleInExternalSystem.getStatusCode().value() != 201) { - throw new Exception("Failed to add Role in External System"); - } else{ - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + throw new Exception(addNewRoleInExternalSystem.getBody()); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Finished adding into External Auth system and status code: {}", + addNewRoleInExternalSystem.getStatusCode().value()); response = true; } return response; } - + + /** + * + * It updates existing role in the External Auth System + * + * @param addRole + * It Contains role information + * @param app + * @return string which is formatted to match with the external auth system + * @throws JsonProcessingException + */ @SuppressWarnings("unchecked") - private String createNewRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException { + private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String addNewRole = ""; ExternalAccessRole extRole = new ExternalAccessRole(); List<EPRole> role = null; String addDesc = null; - if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){ - role = dataAccessService.getList(EPRole.class, - " where role_id = " + addRole.getId(), null, null); - addDesc = "{\"id\":\"" + role.get(0).getId() + "\",\"name\":\"" + addRole.getName() + "\",\"active\":\"" - + role.get(0).getActive() + "\",\"priority\":\"" + role.get(0).getPriority() - + "\",\"appId\":\"null\",\"appRoleId\":\"null\"}"; - } else{ - role = dataAccessService.getList(EPRole.class, - " where app_role_id = " + addRole.getId(), null, null); - addDesc = "{\"id\":\"" + role.get(0).getId() + "\",\"name\":\"" + addRole.getName() + "\",\"active\":\"" - + role.get(0).getActive() + "\",\"priority\":\"" + addRole.getPriority() + "\",\"appId\":\"" - + app.getId() + "\",\"appRoleId\":\"" + role.get(0).getAppRoleId() + "\"}"; + Map<String, Object> extSystemUpdateRole = new LinkedHashMap<>(); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId(), null, null); + } else { + role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId(), null, null); } + extSystemUpdateRole.put(ID, role.get(0).getId()); + extSystemUpdateRole.put(ROLE_NAME, addRole.getName()); + extSystemUpdateRole.put(ACTIVE, role.get(0).getActive()); + extSystemUpdateRole.put(PRIORITY, role.get(0).getPriority()); + extSystemUpdateRole.put(APP_ID, role.get(0).getAppId()); + extSystemUpdateRole.put(APP_ROLE_ID, role.get(0).getAppRoleId()); + addDesc = mapper.writeValueAsString(extSystemUpdateRole); extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_")); extRole.setDescription(addDesc); addNewRole = mapper.writeValueAsString(extRole); return addNewRole; } + /** + * It create a role in the external auth system and then in our local + * + * @param addRoleInDB + * @param app + * @return true else false + * @throws Exception + */ @SuppressWarnings("unchecked") @Transactional private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception { @@ -441,40 +564,39 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic epRoleNew.setAppId(app.getId()); } dataAccessService.saveDomainObject(epRoleNew, null); - List <EPRole> getRoleCreated = null; - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - List<EPRole> roleCreated = dataAccessService.getList(EPRole.class, - " where role_name = '" + addRoleInDB.getName() +"'", null, null); - EPRole epUpdateRole = roleCreated.get(0); - epUpdateRole.setAppRoleId(epUpdateRole.getId()); - dataAccessService.saveDomainObject(epUpdateRole, null); - getRoleCreated = dataAccessService.getList(EPRole.class, - " where role_name = '" + addRoleInDB.getName() +"'", null, null); - } else{ - getRoleCreated = dataAccessService.getList(EPRole.class, - " where role_name = '" + addRoleInDB.getName() +"'", null, null); - } - // Add role in External Access system - boolean response = addNewRoleInExternalSystem(getRoleCreated, app); - - if (!response) { - throw new Exception("Failed to add role!"); + List<EPRole> getRoleCreated = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + List<EPRole> roleCreated = dataAccessService.getList(EPRole.class, + WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null, + null); + EPRole epUpdateRole = roleCreated.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + getRoleCreated = dataAccessService.getList(EPRole.class, + WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null, + null); + } else { + getRoleCreated = dataAccessService.getList(EPRole.class, + WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id is null", null, null); } + // Add role in External Auth system + result = addNewRoleInExternalSystem(getRoleCreated, app); } else { // if role already exists then update it if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { applicationRoles = dataAccessService.getList(EPRole.class, " where app_id is null " + " and role_id = " + addRoleInDB.getId(), null, null); } else { applicationRoles = dataAccessService.getList(EPRole.class, - " where app_id = " + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null); + WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null); } - if(applicationRoles.isEmpty() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + if (applicationRoles.isEmpty()) { applicationRoles = dataAccessService.getList(EPRole.class, - " where app_id = " + app.getId() + " and role_id = " + addRoleInDB.getId(), null, null); + WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + addRoleInDB.getName() + "'", null, + null); } updateRoleInExternalSystem(addRoleInDB, app); deleteRoleFunction(app, applicationRoles); - if (applicationRoles.size() > 0 || !applicationRoles.isEmpty()) { + if (!applicationRoles.isEmpty()) { epRole = applicationRoles.get(0); epRole.setName(addRoleInDB.getName()); epRole.setPriority(addRoleInDB.getPriority()); @@ -482,15 +604,16 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { epRole.setAppId(null); epRole.setAppRoleId(null); - } else if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && applicationRoles.get(0).getAppRoleId() == null){ + } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) + && applicationRoles.get(0).getAppRoleId() == null) { epRole.setAppRoleId(epRole.getId()); } dataAccessService.saveDomainObject(epRole, null); } - + saveRoleFunction(listWithoutDuplicates, app, applicationRoles); + result = true; } - result = true; } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e); throw new Exception(e.getMessage()); @@ -498,20 +621,39 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic return result; } + /** + * + * It validates whether role exists in external auth system + * + * @param checkRole + * @param app + * @throws Exception + * If role exits + */ private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception { HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - String roleName = app.getNameSpace()+"."+checkRole.getName().replaceAll(" ", "_"); + String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(" ", "_"); HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - ResponseEntity<String> checkRoleInExternalSystem = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "roles/"+roleName, HttpMethod.GET, checkRoleEntity, String.class); - if(!checkRoleInExternalSystem.getBody().equals("{}")){ - logger.debug("Role already exists in external system ", checkRoleInExternalSystem.getBody()); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> checkRoleInExternalSystem = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/" + + roleName, HttpMethod.GET, checkRoleEntity, String.class); + if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) { + logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value()); throw new Exception("Role already exists in external system"); - } + } } - private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles) throws Exception { + /** + * It saves list of functions to the role in portal + * + * @param roleFunctionListNew + * @param app + * @param applicationRoles + * @throws Exception + */ + private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles) + throws Exception { for (RoleFunction roleFunc : roleFunctionListNew) { EPAppRoleFunction appRoleFunc = new EPAppRoleFunction(); appRoleFunc.setAppId(app.getId()); @@ -520,20 +662,33 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic dataAccessService.saveDomainObject(appRoleFunc, null); } } - + + /** + * It deletes all EPAppRoleFunction records in the portal + * + * @param app + * @param role + */ @SuppressWarnings("unchecked") private void deleteRoleFunction(EPApp app, List<EPRole> role) { List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.getList(EPAppRoleFunction.class, - " where app_id = " + app.getId() + " and role_id = " + role.get(0).getId(), null, null); - if (!appRoleFunctionList.isEmpty() || appRoleFunctionList.size() > 0) { + WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + role.get(0).getId(), null, null); + if (!appRoleFunctionList.isEmpty()) { for (EPAppRoleFunction approleFunction : appRoleFunctionList) { dataAccessService.deleteDomainObject(approleFunction, null); } } } - + + @Override @SuppressWarnings("unchecked") - public String getUser(String loginId, String uebkey) throws Exception { + public List<EPUser> getUser(String loginId){ + return (List<EPUser>) dataAccessService.getList(EPUser.class, + " where org_user_id = '" + loginId + "'", null, null); + } + + @Override + public String getUserWithRoles(String loginId, String uebkey) throws Exception { final Map<String, String> params = new HashMap<>(); List<EPUser> userList = null; CentralUser cenUser = null; @@ -541,43 +696,42 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic String result = null; try { params.put("orgUserIdValue", loginId); - List<EPApp> appList = (List<EPApp>) getApp(uebkey); - if (appList.size() > 0) { + List<EPApp> appList = getApp(uebkey); + if (!appList.isEmpty()) { app = appList.get(0); - userList = (List<EPUser>) dataAccessService.getList(EPUser.class, - " where org_user_id = '" + loginId + "'", null, null); - if (userList.size() > 0) { + userList = getUser(loginId); + if (!userList.isEmpty()) { EPUser user = userList.get(0); ObjectMapper mapper = new ObjectMapper(); Set<EPUserApp> userAppSet = user.getEPUserApps(); cenUser = createEPUser(user, userAppSet, app); result = mapper.writeValueAsString(cenUser); - } else if (userList.size() == 0) { + } else if (userList.isEmpty()) { throw new Exception("User not found"); } } else { throw new Exception("Application not found"); } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getUser is failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e); throw new Exception(e.getMessage()); } return result; } - + @Override public List<CentralRole> getRolesForApp(String uebkey) throws Exception { - logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getRolesForApp"); + logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp"); List<CentralRole> roleList = new ArrayList<>(); final Map<String, Long> params = new HashMap<>(); try { List<EPApp> app = getApp(uebkey); - List<EPRole> appRolesList = getAppRoles(app.get(0).getId(), null); + List<EPRole> appRolesList = getAppRoles(app.get(0).getId()); createCentralRoleObject(app, appRolesList, roleList, params); } catch (Exception e) { throw new Exception("getRolesForApp Failed", e); } - logger.debug(EELFLoggerDelegate.debugLogger, "Finished getRolesForApp"); + logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished getRolesForApp"); return roleList; } @@ -587,17 +741,26 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic EPApp app = getApp(uebkey).get(0); List<CentralRoleFunction> getRoleFuncList = null; final Map<String, Long> params = new HashMap<>(); - params.put("appId", app.getId()); - //Sync all functions from external system into Ecomp portal DB - logger.debug(EELFLoggerDelegate.debugLogger, "Entering into syncRoleFunctionFromExternalAccessSystem"); + params.put(APP_ID, app.getId()); + // Sync all functions from external system into Ecomp portal DB + logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Entering into syncRoleFunctionFromExternalAccessSystem"); syncRoleFunctionFromExternalAccessSystem(app); - logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem"); + logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Finished syncRoleFunctionFromExternalAccessSystem"); getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); return getRoleFuncList; } + /** + * It returns user detail information which is deep copy of EPUser.class object + * + * @param userInfo + * @param userAppSet + * @param app + * @return + * @throws Exception + */ @SuppressWarnings("unchecked") - public CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception { + private CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception { final Map<String, Long> params = new HashMap<>(); CentralUser userAppList = new CentralUser(); @@ -611,7 +774,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (((epApp.getId().equals(app.getId())) && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))) || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) - && (globalRole.startsWith("global_")))) { + && (globalRole.toLowerCase().startsWith("global_")))) { CentralUserApp cua = new CentralUserApp(); cua.setUserId(null); CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(), @@ -624,21 +787,27 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic epApp.getUebTopicName()); cua.setApp(cenApp); params.put("roleId", userApp.getRole().getId()); - params.put("appId", userApp.getApp().getId()); + params.put(APP_ID, userApp.getApp().getId()); List<CentralRoleFunction> appRoleFunctionList = dataAccessService .executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<CentralRoleFunction>(); + SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>(); for (CentralRoleFunction roleFunc : appRoleFunctionList) { CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), roleFunc.getCode(), roleFunc.getName(), null, null); roleFunctionSet.add(cenRoleFunc); } - CentralRole cenRole = new CentralRole(userApp.getRole().getAppRoleId(), - userApp.getRole().getCreated(), userApp.getRole().getModified(), - userApp.getRole().getCreatedId(), userApp.getRole().getModifiedId(), - userApp.getRole().getRowNum(), userApp.getRole().getName(), - userApp.getRole().getActive(), userApp.getRole().getPriority(), roleFunctionSet, null, - null); + Long userRoleId = null; + if (globalRole.toLowerCase().startsWith("global_") + && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) { + userRoleId = userApp.getRole().getId(); + } else { + userRoleId = userApp.getRole().getAppRoleId(); + } + CentralRole cenRole = new CentralRole(userRoleId, userApp.getRole().getCreated(), + userApp.getRole().getModified(), userApp.getRole().getCreatedId(), + userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(), + userApp.getRole().getName(), userApp.getRole().getActive(), + userApp.getRole().getPriority(), roleFunctionSet, null, null); cua.setRole(cenRole); userAppList.userApps.add(cua); @@ -662,7 +831,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(), userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "createEPUser failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e); throw new Exception(e.getMessage()); } @@ -679,12 +848,12 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic List<EPApp> app = null; try { app = getApp(uebkey); - if (app.isEmpty() || app.size() == 0) { + if (app.isEmpty()) { throw new Exception("Application not found"); } String filter = null; - if (app.get(0).getId() == PortalConstants.PORTAL_APP_ID) { - filter = " where role_id = " + roleId + " and app_id is null "; + if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { + filter = WHERE_ROLE_ID_EQUALS + roleId + " and app_id is null "; } else { filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId(); @@ -696,28 +865,38 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e); throw new Exception(e.getMessage()); } return roleList.get(0); } - + + /** + * + * It returns list of app roles along with role functions and which went through deep copy + * + * @param app + * @param roleInfo + * @param roleList + * @param params + * @return + */ @SuppressWarnings("unchecked") private List<CentralRole> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo, List<CentralRole> roleList, Map<String, Long> params) { for (EPRole role : roleInfo) { params.put("roleId", role.getId()); - params.put("appId", app.get(0).getId()); + params.put(APP_ID, app.get(0).getId()); List<CentralRoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<CentralRoleFunction>(); + SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>(); for (CentralRoleFunction roleFunc : cenRoleFuncList) { CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), roleFunc.getCode(), roleFunc.getName(), null, null); roleFunctionSet.add(cenRoleFunc); } - SortedSet<CentralRole> childRoles = new TreeSet<CentralRole>(); + SortedSet<CentralRole> childRoles = new TreeSet<>(); CentralRole cenRole = null; if (role.getAppRoleId() == null) { cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(), @@ -742,37 +921,47 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic final Map<String, String> params = new HashMap<>(); try { params.put("functionCode", functionCode); - params.put("appId", String.valueOf(app.getId())); + params.put(APP_ID, String.valueOf(app.getId())); getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null); - if (getRoleFuncList.isEmpty() | getRoleFuncList.size() == 0) { + if (getRoleFuncList.isEmpty()) { return roleFunc; } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", e); - throw new Exception("getRoleFunction failed"); + logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e); + throw new Exception("getRoleFunction failed", e); } return getRoleFuncList.get(0); } @Override - public void saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception { + public boolean saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception { + boolean saveOrUpdateFunction = false; try { addRoleFunctionInExternalSystem(domainCentralRoleFunction, app); dataAccessService.saveDomainObject(domainCentralRoleFunction, null); + saveOrUpdateFunction = true; } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction failed", e); - throw new Exception(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e); + saveOrUpdateFunction = false; } + return saveOrUpdateFunction; } - + + /** + * It creates application permission in external auth system + * + * @param domainCentralRoleFunction + * @param app + * @throws Exception + */ @SuppressWarnings("unchecked") private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception { ObjectMapper mapper = new ObjectMapper(); final Map<String, String> params = new HashMap<>(); params.put("functionCd", domainCentralRoleFunction.getCode()); - params.put("appId", String.valueOf(app.getId())); + params.put(APP_ID, String.valueOf(app.getId())); ExternalAccessPerms extPerms = new ExternalAccessPerms(); HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); List<CentralRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("getAppFunctionDetails", params, @@ -785,170 +974,209 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; HttpEntity<String> getSinglePermEntity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} ", CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); ResponseEntity<String> getResponse = template.exchange( SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/" + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*", HttpMethod.GET, getSinglePermEntity, String.class); if (getResponse.getStatusCode().value() != 200) { + EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode()); throw new Exception(getResponse.getBody()); } - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished GET permission from External Auth system and response: {} ", getResponse.getBody()); String res = getResponse.getBody(); - if (res.equals("{}")) { - try{ - extPerms.setAction("*"); - extPerms.setInstance(domainCentralRoleFunction.getCode()); - extPerms.setType(app.getNameSpace() + "." + checkType); - extPerms.setDescription(domainCentralRoleFunction.getName()); - String updateRole = mapper.writeValueAsString(extPerms); - HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", - HttpMethod.POST, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); - }catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to add fucntion in external central auth system", e); + if (res.equals(IS_EMPTY_JSON_STRING)) { + try { + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> addPermResponse= template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission in and status code: {} ", addPermResponse.getStatusCode().value()); + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + }catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", + e); } } else { - try{ - extPerms.setAction("*"); - extPerms.setInstance(domainCentralRoleFunction.getCode()); - extPerms.setType(app.getNameSpace() + "." + checkType); - extPerms.setDescription(domainCentralRoleFunction.getName()); - String updateRole = mapper.writeValueAsString(extPerms); - HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", - HttpMethod.PUT, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); - } catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to add fucntion in external central auth system", e); - + try { + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> updatePermResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.PUT, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system and response: {} ", updatePermResponse.getBody()); + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system", + e); } } } @Override @Transactional - public void deleteCentralRoleFunction(String code, String uebkey) { + public boolean deleteCentralRoleFunction(String code, EPApp app) { + boolean deleteFunctionResponse = false; try { - EPApp app = getApp(uebkey).get(0); final Map<String, String> params = new HashMap<>(); params.put("functionCd", code); - params.put("appId", String.valueOf(app.getId())); - CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService.executeNamedQuery("getAppFunctionDetails", params, null).get(0); - deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app); - //Delete role function dependecy records - deleteAppRoleFunctions(code, app); + params.put(APP_ID, String.valueOf(app.getId())); + CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService + .executeNamedQuery("getAppFunctionDetails", params, null).get(0); + deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app); + // Delete role function dependency records + deleteAppRoleFunctions(code, app); dataAccessService.deleteDomainObject(domainCentralRoleFunction, null); + deleteFunctionResponse = true; } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e); } + return deleteFunctionResponse; } + /** + * It deletes app function record in portal + * + * @param code + * @param app + */ private void deleteAppRoleFunctions(String code, EPApp app) { - dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = "+app.getId()+" and function_cd = '"+ code +"'", null); + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, + APP_ID_EQUALS + app.getId() + " and function_cd = '" + code + "'", null); } - + + /** + * + * It deletes permission in the external auth system + * + * @param domainCentralRoleFunction + * @param app + * @throws Exception + */ private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception { - try{ - ObjectMapper mapper = new ObjectMapper(); - ExternalAccessPerms extPerms = new ExternalAccessPerms(); - String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - extPerms.setAction("*"); - extPerms.setInstance(domainCentralRoleFunction.getCode()); - extPerms.setType(app.getNameSpace() + "." + checkType); - extPerms.setDescription(domainCentralRoleFunction.getName()); - String updateRole = mapper.writeValueAsString(extPerms); - HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm?force=true", - HttpMethod.DELETE, entity, String.class); - } catch(Exception e){ - if(e.getMessage().equalsIgnoreCase("404 Not Found")){ - logger.debug(EELFLoggerDelegate.debugLogger, " It seems like function is already deleted in external central auth system but exists in local DB", e.getMessage()); - } else{ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to delete functions in External System", e); + try { + ObjectMapper mapper = new ObjectMapper(); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger,"deleteRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> delPermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "perm?force=true", HttpMethod.DELETE, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system and status code: {} ", delPermResponse.getStatusCode().value()); + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.debugLogger, + " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB", + e.getMessage()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e); } } } @Override - public void saveRoleForApplication(Role saveRole, String uebkey) throws Exception { + public boolean saveRoleForApplication(Role saveRole, String uebkey) throws Exception { + boolean addRoleResponse = false; try { EPApp app = getApp(uebkey).get(0); addRoleInEcompDB(saveRole, app); + addRoleResponse = true; } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e); - throw new Exception(e.getMessage()); } + return addRoleResponse; } @SuppressWarnings("unchecked") @Override - public void deleteRoleForApplication(String deleteRole, String uebkey) throws Exception { - Session localSession = null; + public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception { + Session localSession = sessionFactory.openSession(); Transaction transaction = null; boolean result = false; try { - localSession = sessionFactory.openSession(); transaction = localSession.beginTransaction(); List<EPRole> epRoleList = null; ResponseEntity<String> deleteResponse = null; EPApp app = getApp(uebkey).get(0); - if(app.getId() == 1) - { + if (app.getId() == 1) { epRoleList = dataAccessService.getList(EPRole.class, - " where app_id is null " + "and role_name = '" + deleteRole +"'", null, null); - } - else{ - epRoleList = dataAccessService.getList(EPRole.class, - " where app_id = " + app.getId() + " and role_name = '" + deleteRole +"'", null, null); + " where app_id is null " + "and role_name = '" + deleteRole + "'", null, null); + } else { + epRoleList = dataAccessService.getList(EPRole.class, + WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + deleteRole + "'", null, null); } // Delete app role functions before deleting role deleteRoleFunction(app, epRoleList); - if(app.getId() == 1) - { + if (app.getId() == 1) { // Delete fn_user_ role dataAccessService.deleteDomainObjects(EPUserApp.class, - " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); - - deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId()); + APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); + + deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId()); } // Delete Role in External System String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}"; deleteResponse = deleteRoleInExternalSystem(deleteRoleKey); - if (deleteResponse.getStatusCode().value() != 200) { - throw new Exception("Failed to delete role in external access system!"); + if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) { + EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode()); + logger.error(EELFLoggerDelegate.errorLogger, + "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ", + deleteResponse.getBody()); } - logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction"); transaction.commit(); - logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction"); dataAccessService.deleteDomainObject(epRoleList.get(0), null); result = true; } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication failed", e); - throw new Exception(e.getMessage()); - }finally { + logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e); + result = false; + } finally { localSession.close(); - if (!result) { - throw new Exception( - "Exception occurred in deleteRoleForApplication while closing database session for role: '" + deleteRole + "'."); - } } + return result; } + /** + * + * It deletes application user role in external auth system + * + * @param role + * @param app + * @param LoginId + * @throws Exception + */ private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception { HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); ResponseEntity<String> getResponse = template .exchange( SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/" @@ -957,14 +1185,14 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"), HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody()); if (getResponse.getStatusCode().value() != 200) { throw new Exception(getResponse.getBody()); } - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); String res = getResponse.getBody(); - if (!res.equals("{}")) { + if (!res.equals(IS_EMPTY_JSON_STRING)) { HttpEntity<String> userRoleentity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); ResponseEntity<String> deleteResponse = template .exchange( SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) @@ -976,7 +1204,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (deleteResponse.getStatusCode().value() != 200) { throw new Exception("Failed to delete user role"); } - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value()); } } @@ -993,10 +1221,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic appId = app.get(0).getId(); } List<EPRole> epRole = dataAccessService.getList(EPRole.class, - " where app_id = " + appId + " and active_yn = 'Y'", null, null); + WHERE_APP_ID_EQUALS + appId + " and active_yn = 'Y'", null, null); roleList = createCentralRoleObject(app, epRole, roleList, params); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e); throw new Exception(e.getMessage()); } return roleList; @@ -1005,156 +1233,169 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic @SuppressWarnings("unchecked") @Override - public void deleteDependcyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception { + public boolean deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception { boolean result = false; - Session localSession = null; + Session localSession = sessionFactory.openSession(); Transaction transaction = null; EPApp app = null; try { - localSession = sessionFactory.openSession(); transaction = localSession.beginTransaction(); List<EPRole> epRoleList = null; app = getApp(uebkey).get(0); epRoleList = dataAccessService.getList(EPRole.class, - " where app_id = " + app.getId() + " and app_role_id = " + roleId, null, null); - if(epRoleList.isEmpty()){ + WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + roleId, null, null); + if (epRoleList.isEmpty()) { epRoleList = dataAccessService.getList(EPRole.class, - " where app_id = " + app.getId() + " and role_id = " + roleId, null, null); + WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + roleId, null, null); } // Delete User Role in External System before deleting role deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId); // Delete user app roles dataAccessService.deleteDomainObjects(EPUserApp.class, - " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); - - deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId()); - logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); + + deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: about to commit the transaction"); transaction.commit(); - logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction"); result = true; + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to deleteRoleDependeciesRecord", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); } catch (Exception e) { - EcompPortalUtils.rollbackTransaction(transaction, - "deleteDependcyRoleRecord rollback, exception = " + e); + EcompPortalUtils.rollbackTransaction(transaction, "deleteDependencyRoleRecord: rollback, exception = " + e); logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); - }finally { + result = false; + } finally { localSession.close(); - if (!result) { - throw new Exception( - "Exception occurred in syncAppRoles while closing database session for role: '" + app.getId() + "'."); - } } + return result; } + @Override @SuppressWarnings("unchecked") @Transactional - public void syncRoleFunctionFromExternalAccessSystem(EPApp app){ - try{ - ResponseEntity<String> response = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); - - String res = response.getBody(); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res); - JSONObject jsonObj = new JSONObject(res); - JSONArray extPerms = jsonObj.getJSONArray("perm"); - for (int i = 0; i < extPerms.length(); i++) { - if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) { - extPerms.remove(i); - i--; + public void syncRoleFunctionFromExternalAccessSystem(EPApp app) { + try { + ResponseEntity<String> response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + response = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + + String res = response.getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ", response.getBody()); + JSONObject jsonObj = new JSONObject(res); + JSONArray extPerms = jsonObj.getJSONArray("perm"); + for (int i = 0; i < extPerms.length(); i++) { + if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) { + extPerms.remove(i); + i--; + } } - } - ExternalAccessPermsDetail permDetails = null; - List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>(); - for (int i = 0; i < extPerms.length(); i++) { - if (extPerms.getJSONObject(i).has("roles")) { - ObjectMapper rolesListMapper = new ObjectMapper(); - JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles"); - List<String> list = rolesListMapper.readValue(resRoles.toString(), - TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); - permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), - extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"), - list, extPerms.getJSONObject(i).getString("description")); - permsDetailList.add(permDetails); - } else { - permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), - extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"), - extPerms.getJSONObject(i).getString("description")); - permsDetailList.add(permDetails); + ExternalAccessPermsDetail permDetails = null; + List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>(); + for (int i = 0; i < extPerms.length(); i++) { + if (extPerms.getJSONObject(i).has("roles")) { + ObjectMapper rolesListMapper = new ObjectMapper(); + JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles"); + List<String> list = rolesListMapper.readValue(resRoles.toString(), + TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); + permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), + extPerms.getJSONObject(i).getString("instance"), + extPerms.getJSONObject(i).getString("action"), list, + extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION)); + permsDetailList.add(permDetails); + } else { + permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), + extPerms.getJSONObject(i).getString("instance"), + extPerms.getJSONObject(i).getString("action"), + extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION)); + permsDetailList.add(permDetails); + } } - } - final Map<String, Long> params = new HashMap<>(); - final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>(); - params.put("appId", app.getId()); - List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, - null); - if (appFunctions.size() > 0) { - for (CentralRoleFunction roleFunc : appFunctions) { - roleFuncMap.put(roleFunc.getCode(), roleFunc); - } - } - // delete all application role functions - dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null); - - // Add if new functions and app role functions were added in Externalsystem - for (ExternalAccessPermsDetail permsDetail : permsDetailList) { - if (!roleFuncMap.containsKey(permsDetail.getInstance())) { - CentralRoleFunction addFunction = new CentralRoleFunction(); - addFunction.setAppId(app.getId()); - addFunction.setCode(permsDetail.getInstance()); - addFunction.setName(permsDetail.getDescription()); - dataAccessService.saveDomainObject(addFunction, null); + final Map<String, Long> params = new HashMap<>(); + final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>(); + params.put(APP_ID, app.getId()); + List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, + null); + if (!appFunctions.isEmpty()) { + for (CentralRoleFunction roleFunc : appFunctions) { + roleFuncMap.put(roleFunc.getCode(), roleFunc); + } } + // delete all application role functions + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null); + + // Add if new functions and app role functions were added in external auth system + for (ExternalAccessPermsDetail permsDetail : permsDetailList) { + if (!roleFuncMap.containsKey(permsDetail.getInstance())) { + try{ + CentralRoleFunction addFunction = new CentralRoleFunction(); + addFunction.setAppId(app.getId()); + addFunction.setCode(permsDetail.getInstance()); + addFunction.setName(permsDetail.getDescription()); + dataAccessService.saveDomainObject(addFunction, null); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed to add function", e); + } + } List<EPRole> epRolesList = null; List<String> roles = permsDetail.getRoles(); if (roles != null) { - for (String roleList : roles) { - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - epRolesList = dataAccessService.getList(EPRole.class, - " where app_id is null " + " and role_name = '" - + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'", - null, null); - } else { - epRolesList = dataAccessService.getList(EPRole.class, - " where app_id = " + app.getId() + " and role_name = '" - + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'", - null, null); - } - if(epRolesList.isEmpty()){ + for (String roleList : roles) { if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { epRolesList = dataAccessService.getList(EPRole.class, " where app_id is null " + " and role_name = '" - + roleList.substring(app.getNameSpace().length() + 1) + + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") + "'", null, null); } else { epRolesList = dataAccessService.getList(EPRole.class, - " where app_id = " + app.getId() + " and role_name = '" - + roleList.substring(app.getNameSpace().length() + 1)+"'", + WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") + + "'", null, null); } - } - // save all application role functions - if (epRolesList.size() > 0 || !epRolesList.isEmpty()) { - EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); - addAppRoleFunc.setAppId(app.getId()); - addAppRoleFunc.setCode(permsDetail.getInstance()); - addAppRoleFunc.setRoleId(epRolesList.get(0).getId()); - dataAccessService.saveDomainObject(addAppRoleFunc, null); + if (epRolesList.isEmpty()) { + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id is null " + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1) + "'", + null, null); + } else { + epRolesList = dataAccessService.getList(EPRole.class, + WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1) + "'", + null, null); + } + } + // save all application role functions + if (!epRolesList.isEmpty()) { + try{ + EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); + addAppRoleFunc.setAppId(app.getId()); + addAppRoleFunc.setCode(permsDetail.getInstance()); + addAppRoleFunc.setRoleId(epRolesList.get(0).getId()); + dataAccessService.saveDomainObject(addAppRoleFunc, null); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e); + } + } } } } - } - logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem"); - } catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed syncRoleFunctionFromExternalAccessSystem", e); + logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e); } } - + + @Override @SuppressWarnings("unchecked") public Integer bulkUploadFunctions(String uebkey) throws Exception { EPApp app = getApp(uebkey).get(0); @@ -1168,15 +1409,19 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic addRoleFunctionInExternalSystem(cenRoleFunc, app); functionsAdded++; } + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e.getMessage(), e); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e); } return functionsAdded; } + @Override public Integer bulkUploadRoles(String uebkey) throws Exception { List<EPApp> app = getApp(uebkey); - List<EPRole> roles = getAppRoles(app.get(0).getId(), null); + List<EPRole> roles = getAppRoles(app.get(0).getId()); List<CentralRole> cenRoleList = new ArrayList<>(); final Map<String, Long> params = new HashMap<>(); Integer rolesListAdded = 0; @@ -1192,75 +1437,100 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic rolesListAdded++; } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e); throw new Exception(e.getMessage()); } return rolesListAdded; } - + + /** + * It creating new role in external auth system while doing bulk upload + * + * @param role + * @param app + * @throws Exception + */ private void addRoleInExternalSystem(Role role, EPApp app) throws Exception { - String addRoleNew = createNewRoleInExternalSystem(role, app); + String addRoleNew = updateExistingRoleInExternalSystem(role, app); HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - try{ - HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", - HttpMethod.POST, entity, String.class); - } catch(Exception e){ + try { + HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { if (e.getMessage().equalsIgnoreCase("409 Conflict")) { - logger.error(EELFLoggerDelegate.errorLogger, "Role already exits but does not break functionality"); + logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e); } else { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleInExternalSystem", e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage()); } } } - + + @Override @SuppressWarnings("unchecked") public Integer bulkUploadRolesFunctions(String uebkey) throws Exception { EPApp app = getApp(uebkey).get(0); - List<EPRole> roles = getAppRoles(app.getId(), null); + List<EPRole> roles = getAppRoles(app.getId()); final Map<String, Long> params = new HashMap<>(); Integer roleFunctions = 0; try { for (EPRole role : roles) { params.put("roleId", role.getId()); - List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null); - if(!appRoleFunc.isEmpty()){ - for(BulkUploadRoleFunction addRoleFunc : appRoleFunc){ + List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions", + params, null); + if (!appRoleFunc.isEmpty()) { + for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) { addRoleFunctionsInExternalSystem(addRoleFunc, role, app); roleFunctions++; } } } + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e); } return roleFunctions; } - - private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app){ - String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; - ExternalAccessRolePerms extRolePerms = null; - ExternalAccessPerms extPerms = null; - ObjectMapper mapper = new ObjectMapper(); - try{ + + /** + * Its adding a role function while doing bulk upload + * + * @param addRoleFunc + * @param role + * @param app + */ + private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) { + String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + ExternalAccessRolePerms extRolePerms = null; + ExternalAccessPerms extPerms = null; + ObjectMapper mapper = new ObjectMapper(); + try { HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*", addRoleFunc.getFunctionName()); + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*", + addRoleFunc.getFunctionName()); extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName().replaceAll(" ", "_")); String updateRolePerms = mapper.writeValueAsString(extRolePerms); HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); - template - .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role/perm", HttpMethod.POST, entity, String.class); - } catch(Exception e){ - if (e.getMessage().equalsIgnoreCase("409 Conflict")) { - logger.error(EELFLoggerDelegate.errorLogger, "RoleFunction already exits but does not break functionality",e); - } else { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem", e.getMessage()); - } + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", + HttpMethod.POST, entity, String.class); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, + "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", + e.getMessage()); } + } } @Override @@ -1316,143 +1586,143 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } catch (Exception e) { if (e.getMessage().equalsIgnoreCase("409 Conflict")) { logger.error(EELFLoggerDelegate.errorLogger, - "RoleFunction already exits but does not break functionality"); + "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality"); } else { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem", + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem", e.getMessage()); } } } } - + + @Override @SuppressWarnings("unchecked") @Transactional - public void SyncApplicationRolesWithEcompDB(EPApp app){ - try{ - ResponseEntity<String> response = null; - List<EPRole> finalRoleList = new ArrayList<>(); - ExternalRoleDescription ApplicationRole = new ExternalRoleDescription(); - ExternalAccessPerms externalAccessPerms = null; - List<String> functionCodelist = new ArrayList<>(); - List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); - String res = response.getBody(); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res); - JSONObject jsonObj = new JSONObject(res); - JSONArray extRole = jsonObj.getJSONArray("role"); - for (int i = 0; i < extRole.length(); i++) { - if (extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin") - || extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner") - ) { - extRole.remove(i); - i--; - } - if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get("name").equals(app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))){ - extRole.remove(i); - i--; - } - } - List<EPAppRoleFunction> applicationRoleFunctionList = new ArrayList<>(); - for (int i = 0; i < extRole.length(); i++) { - ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails(); - EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction(); - JSONObject Role = (JSONObject) extRole.get(i); - if(!extRole.getJSONObject(i).has("description")) - { - ApplicationRole.setActive("true"); - ApplicationRole.setAppId("null"); - ApplicationRole.setPriority("null"); - ApplicationRole.setAppRoleId("null"); - String roleName =extRole.getJSONObject(i).getString("name"); - ApplicationRole.setName(roleName.substring(app.getNameSpace().length()+1)); - } - else { - String desc = extRole.getJSONObject(i).getString("description"); - ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class); + public void syncApplicationRolesWithEcompDB(EPApp app) { + try { + ResponseEntity<String> response = null; + List<EPRole> finalRoleList = new ArrayList<>(); + ExternalRoleDescription ApplicationRole = new ExternalRoleDescription(); + ExternalAccessPerms externalAccessPerms = null; + List<String> functionCodelist = new ArrayList<>(); + List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + response = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + String res = response.getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :", + res); + JSONObject jsonObj = new JSONObject(res); + JSONArray extRole = jsonObj.getJSONArray("role"); + for (int i = 0; i < extRole.length(); i++) { + if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ".admin") + || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ".owner")) { + extRole.remove(i); + i--; + } + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get(ROLE_NAME) + .equals(app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))) { + extRole.remove(i); + i--; + } } - + List<EPAppRoleFunction> applicationRoleFunctionList = new ArrayList<>(); + for (int i = 0; i < extRole.length(); i++) { + ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails(); + EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction(); + JSONObject Role = (JSONObject) extRole.get(i); + if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) { + ApplicationRole.setActive("true"); + ApplicationRole.setAppId(IS_NULL_STRING); + ApplicationRole.setPriority(IS_NULL_STRING); + ApplicationRole.setAppRoleId(IS_NULL_STRING); + String roleName = extRole.getJSONObject(i).getString(ROLE_NAME); + ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1)); + } else { + String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); + ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class); + } - SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>(); - if (extRole.getJSONObject(i).has("perms")) { - JSONArray extPerm = (JSONArray) Role.get("perms"); - for (int j = 0; j < extPerm.length(); j++) { - JSONObject perms = extPerm.getJSONObject(j); - externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), perms.getString("instance"), - perms.getString("action")); - ePAppRoleFunction.setCode(externalAccessPerms.getInstance()); - functionCodelist.add(ePAppRoleFunction.getCode()); - externalAccessPermsOfRole.add(externalAccessPerms); + SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>(); + if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) { + JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS); + for (int j = 0; j < extPerm.length(); j++) { + JSONObject perms = extPerm.getJSONObject(j); + externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), + perms.getString("instance"), perms.getString("action")); + ePAppRoleFunction.setCode(externalAccessPerms.getInstance()); + functionCodelist.add(ePAppRoleFunction.getCode()); + externalAccessPermsOfRole.add(externalAccessPerms); + } } - } - if (ApplicationRole.getActive().equals("null")) { - externalRoleDetail.setActive(false); - } else { - externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString())); - } - externalRoleDetail.setName(ApplicationRole.getName()); - - if (ApplicationRole.getAppId().equals("null") && app.getId() == 1) { - externalRoleDetail.setAppId(null); - } else if(ApplicationRole.getAppId().equals("null")){ - externalRoleDetail.setAppId(app.getId()); - }else { - externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString())); + if (ApplicationRole.getActive().equals(IS_NULL_STRING)) { + externalRoleDetail.setActive(false); + } else { + externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString())); + } + externalRoleDetail.setName(ApplicationRole.getName()); + + if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) { + externalRoleDetail.setAppId(null); + } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) { + externalRoleDetail.setAppId(app.getId()); + } else { + externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString())); + } + + if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) { + externalRoleDetail.setPriority(null); + } else { + externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString())); + } + + if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) { + externalRoleDetail.setAppRoleId(null); + } + + if (!externalAccessPermsOfRole.isEmpty()) { + for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) { + EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); + apRoleFunction.setAppId(app.getId()); + apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId())); + apRoleFunction.setCode(externalpermission.getInstance()); + applicationRoleFunctionList.add(apRoleFunction); + } + } + externalRoleDetailsList.add(externalRoleDetail); } - if (ApplicationRole.getPriority().equals("null")) { - externalRoleDetail.setPriority(null); - } else { - externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString())); + for (ExternalRoleDetails externalRole : externalRoleDetailsList) { + EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole); + finalRoleList.add(ecompRole); } - if (ApplicationRole.getAppRoleId().equals("null") && app.getId() == 1) { - externalRoleDetail.setAppRoleId(null); + List<EPRole> applicationRolesList = new ArrayList<>(); + applicationRolesList = getAppRoles(app.getId()); + List<String> applicationRoleIdList = new ArrayList<>(); + for (EPRole applicationRole : applicationRolesList) { + applicationRoleIdList.add(applicationRole.getName()); } - if (!externalAccessPermsOfRole.isEmpty() || externalAccessPermsOfRole.size() > 0) { - for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) { - EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); - apRoleFunction.setAppId(app.getId()); - apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId())); - apRoleFunction.setCode(externalpermission.getInstance()); - applicationRoleFunctionList.add(apRoleFunction); + List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>(); + for (EPRole aafRole : finalRoleList) { + if (!applicationRoleIdList.contains(aafRole.getName())) { + roleListToBeAddInEcompDB.add(aafRole); } } - externalRoleDetailsList.add(externalRoleDetail); - } - - for (ExternalRoleDetails externalRole : externalRoleDetailsList) { - EPRole ecompRole = new EPRole(); - ecompRole = convertExternalRoleDetailstoEpRole(externalRole); - finalRoleList.add(ecompRole); - } - List<EPRole> applicationRolesList = new ArrayList<>(); - applicationRolesList = getAppRoles(app.getId(), null); - List<String> applicationRoleIdList = new ArrayList<>(); - for (EPRole applicationRole : applicationRolesList) { - applicationRoleIdList.add(applicationRole.getName()); - } - - List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>(); - for (EPRole aafRole : finalRoleList) { - if (!applicationRoleIdList.contains(aafRole.getName())) { - roleListToBeAddInEcompDB.add(aafRole); + // Check if roles exits in external Access system and make it + // inactive + final Map<String, EPRole> checkRolesInactive = new HashMap<>(); + for (EPRole extrole : finalRoleList) { + checkRolesInactive.put(extrole.getName(), extrole); } - } - - // Check if roles exits in external Access system and make it inactive - final Map<String, EPRole> checkRolesInactive = new HashMap<>(); - for(EPRole extrole : finalRoleList){ - checkRolesInactive.put(extrole.getName(), extrole); - } for (EPRole role : applicationRolesList) { final Map<String, String> extRoleParams = new HashMap<>(); List<EPRole> roleList = new ArrayList<>(); @@ -1461,15 +1731,15 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (app.getId() == 1) { roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null); } else { - extRoleParams.put("appId", app.getId().toString()); + extRoleParams.put(APP_ID, app.getId().toString()); roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null); } EPRole updateRoleInactive = roleList.get(0); updateRoleInactive.setActive(false); - dataAccessService.saveDomainObject(updateRoleInactive, null); + dataAccessService.saveDomainObject(updateRoleInactive, null); } } - + for (EPRole roleItem : finalRoleList) { final Map<String, String> roleParams = new HashMap<>(); List<EPRole> currentList = new ArrayList<>(); @@ -1477,7 +1747,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (app.getId() == 1) { currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null); } else { - roleParams.put("appId", app.getId().toString()); + roleParams.put(APP_ID, app.getId().toString()); currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null); } @@ -1502,52 +1772,60 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } } - EPRole roleToBeAddedInEcompDB = new EPRole(); - for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) { - roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i); - if(app.getId() == 1) - { - roleToBeAddedInEcompDB.setAppRoleId(null); - } - dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null); - List <EPRole> getRoleCreatedInSync = null; - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - getRoleCreatedInSync = dataAccessService.getList(EPRole.class, - " where role_name = '" + roleToBeAddedInEcompDB.getName() +"'", null, null); - EPRole epUpdateRole = getRoleCreatedInSync.get(0); - epUpdateRole.setAppRoleId(epUpdateRole.getId()); - dataAccessService.saveDomainObject(epUpdateRole, null); - } - List<EPRole> roleList = new ArrayList<>(); - final Map<String, String> params = new HashMap<>(); + EPRole roleToBeAddedInEcompDB = new EPRole(); + for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) { + roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i); + if (app.getId() == 1) { + roleToBeAddedInEcompDB.setAppRoleId(null); + } + dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null); + List<EPRole> getRoleCreatedInSync = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + getRoleCreatedInSync = dataAccessService.getList(EPRole.class, + WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "'", null, null); + EPRole epUpdateRole = getRoleCreatedInSync.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + } + List<EPRole> roleList = new ArrayList<>(); + final Map<String, String> params = new HashMap<>(); - params.put("appRoleName", roleToBeAddedInEcompDB.getName()); - if (app.getId() == 1) { - roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null); - } else { - params.put("appId", app.getId().toString()); - roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null); + params.put("appRoleName", roleToBeAddedInEcompDB.getName()); + if (app.getId() == 1) { + roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null); + } else { + params.put(APP_ID, app.getId().toString()); + roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null); + } + EPRole role = roleList.get(0); + Role aaFrole = new Role(); + aaFrole.setId(role.getId()); + aaFrole.setActive(role.getActive()); + aaFrole.setPriority(role.getPriority()); + aaFrole.setName(role.getName()); + updateRoleInExternalSystem(aaFrole, app); } - EPRole role = roleList.get(0); - Role aaFrole = new Role(); - aaFrole.setId(role.getId()); - aaFrole.setActive(role.getActive()); - aaFrole.setPriority(role.getPriority()); - aaFrole.setName(role.getName()); - updateRoleInExternalSystem(aaFrole, app); - } - dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null); + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null); for (EPAppRoleFunction rolefun : applicationRoleFunctionList) { dataAccessService.saveDomainObject(rolefun, null); } - - logger.debug(EELFLoggerDelegate.debugLogger, "Finished SyncApplicationRolesWithEcompDB"); - }catch(Exception e){ + logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished"); + } catch(HttpClientErrorException e){ logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e); } } - public EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) { + /** + * + * It converts from ExternalRoleDetails.class object to EPRole.class object + * + * @param externalRoleDetails + * @return EPRole object + */ + private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) { EPRole role = new EPRole(); role.setActive(externalRoleDetails.isActive()); role.setAppId(externalRoleDetails.getAppId()); @@ -1575,102 +1853,115 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic return userRolesAdded; } - private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload){ - try{ - String name = ""; - ObjectMapper mapper = new ObjectMapper(); - if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { - name = userRolesUpload.getOrgUserId() - + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); - } - ExternalAccessUser extUser = new ExternalAccessUser(name, - userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_")); - String userRole = mapper.writeValueAsString(extUser); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(userRole, headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", - HttpMethod.POST, entity, String.class); + /** + * Its adding a user role in external auth system while doing bulk upload + * + * @param userRolesUpload + */ + private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) { + try { + String name = ""; + ObjectMapper mapper = new ObjectMapper(); + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = userRolesUpload.getOrgUserId() + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + ExternalAccessUser extUser = new ExternalAccessUser(name, + userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_")); + String userRole = mapper.writeValueAsString(extUser); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, entity, String.class); + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); } catch (Exception e) { if (e.getMessage().equalsIgnoreCase("409 Conflict")) { - logger.error(EELFLoggerDelegate.errorLogger, "UserRole already exits but does not break functionality"); + logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality"); } else { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to addUserRoleInExternalSystem", e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e.getMessage()); } } } @Override - public void deleteRoleDependeciesRecord(Session localSession, Long roleId) throws Exception { + public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId) throws Exception { try { + String sql = ""; + Query query = null; + + //It should delete only when it portal's roleId + if(appId.equals(PortalConstants.PORTAL_APP_ID)){ // Delete from fn_role_function - String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; + sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - Query query = localSession.createSQLQuery(sql); + query = localSession.createSQLQuery(sql); query.executeUpdate(); - // Delete from ep_app_role_function - sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId; + // Delete from fn_role_composite + sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId; logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); + query = localSession.createSQLQuery(sql); query.executeUpdate(); + } - // Delete from ep_role_notification - sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId; + // Delete from ep_app_role_function + sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId; logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); query = localSession.createSQLQuery(sql); query.executeUpdate(); - - // Delete from fn_role_composite - sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" - + roleId; + + // Delete from ep_role_notification + sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId; logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); query = localSession.createSQLQuery(sql); query.executeUpdate(); - + // Delete from fn_user_pseudo_role sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); query = localSession.createSQLQuery(sql); query.executeUpdate(); - - //Delete form EP_WIDGET_CATALOG_ROLE + + // Delete form EP_WIDGET_CATALOG_ROLE sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId; logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); query = localSession.createSQLQuery(sql); query.executeUpdate(); - - //Delete form EP_WIDGET_CATALOG_ROLE + + // Delete form EP_WIDGET_CATALOG_ROLE sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId; logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); query = localSession.createSQLQuery(sql); query.executeUpdate(); - - //Delete form fn_menu_functional_roles + + // Delete form fn_menu_functional_roles sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId; logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); query = localSession.createSQLQuery(sql); query.executeUpdate(); - + } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord failed " , e); - throw new Exception("delete Failed"+ e.getMessage()); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e); + throw new Exception("delete Failed" + e.getMessage()); } - + } - @SuppressWarnings("unchecked") @Override public List<String> getMenuFunctionsList(String uebkey) throws Exception { List<String> appMenuFunctionsList = null; - try{ - EPApp app = getApp(uebkey).get(0); - final Map<String, Long> appParams = new HashMap<>(); - appParams.put("appId", app.getId()); - appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null); - } catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed getMenuFunctionsList", e); + try { + EPApp app = getApp(uebkey).get(0); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put(APP_ID, app.getId()); + appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e); return appMenuFunctionsList; } return appMenuFunctionsList; diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java index 1315c5e9..d7aac633 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -435,7 +435,6 @@ public class UserRolesCommonServiceImpl { protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception { logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId); HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles); - boolean result = false; Session localSession = null; Transaction transaction = null; @@ -467,21 +466,10 @@ public class UserRolesCommonServiceImpl { } } Collection<EcompRole> newRolesToAdd = newRolesMap.values(); - for (EcompRole role : newRolesToAdd) { - logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString()); - EPRole newRole = new EPRole(); - // Attention! All roles from remote application supposed to be - // active! - newRole.setActive(true); - newRole.setName(role.getName()); - newRole.setAppId(appId); - newRole.setAppRoleId(role.getId()); - localSession.save(newRole); - } if (obsoleteRoles.size() > 0) { - logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete"); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete"); for (EPRole role : obsoleteRoles) { - logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString()); Long roleId = role.getId(); // delete obsolete roles here // Must delete all records with foreign key constraints on @@ -497,13 +485,13 @@ public class UserRolesCommonServiceImpl { "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) .list(); - logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size()); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size()); for (EPUserApp userRole : userRoles) { logger.debug(EELFLoggerDelegate.debugLogger, - "about to delete userRole: " + userRole.toString()); + "syncAppRoles: about to delete userRole: " + userRole.toString()); localSession.delete(userRole); logger.debug(EELFLoggerDelegate.debugLogger, - "finished deleting userRole: " + userRole.toString()); + "syncAppRoles: finished deleting userRole: " + userRole.toString()); } // Delete from fn_menu_functional_roles @@ -513,7 +501,7 @@ public class UserRolesCommonServiceImpl { .list(); int numMenuRoles = funcMenuRoles.size(); logger.debug(EELFLoggerDelegate.debugLogger, - "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); + "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); for (FunctionalMenuRole funcMenuRole : funcMenuRoles) { Long menuId = funcMenuRole.menuId; // If this is the only role for this menu item, then the @@ -525,14 +513,14 @@ public class UserRolesCommonServiceImpl { .list(); int numMenuRoles2 = funcMenuRoles2.size(); logger.debug(EELFLoggerDelegate.debugLogger, - "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); + "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); localSession.delete(funcMenuRole); if (numMenuRoles2 == 1) { // If this is the only role for this menu item, then // the app and roles will be gone, // so must null out the url too, to be consistent logger.debug(EELFLoggerDelegate.debugLogger, - "There is exactly 1 menu item for this role, so emptying the url"); + "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url"); @SuppressWarnings("unchecked") List<FunctionalMenuItem> funcMenuItems = localSession .createQuery( @@ -546,26 +534,33 @@ public class UserRolesCommonServiceImpl { } } } - externalAccessRolesService.deleteRoleDependeciesRecord(localSession, roleId); - logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString()); + externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString()); localSession.delete(role); - logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role"); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role"); } } - logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + for (EcompRole role : newRolesToAdd) { + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString()); + EPRole newRole = new EPRole(); + // Attention! All roles from remote application supposed to be + // active! + newRole.setActive(true); + newRole.setName(role.getName()); + newRole.setAppId(appId); + newRole.setAppRoleId(role.getId()); + localSession.save(newRole); + } + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction"); transaction.commit(); - logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); - result = true; + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction"); } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); EcompPortalUtils.rollbackTransaction(transaction, - "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + "syncAppRoles: Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + throw new Exception(e); } finally { localSession.close(); - if (!result) { - throw new Exception( - "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'."); - } } } @@ -771,9 +766,10 @@ public class UserRolesCommonServiceImpl { * @param mapper * @param searchService * @param applicationsRestClientService + * @return * @throws Exception */ - private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{ + private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{ EPUser addRemoteUser = null; if (remoteUserShouldBeCreated(roleInAppForUserList)) { @@ -787,6 +783,7 @@ public class UserRolesCommonServiceImpl { // return null; } } + return addRemoteUser; } /** @@ -865,7 +862,7 @@ public class UserRolesCommonServiceImpl { userRolesInLocalApp); List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles; // Apply changes in external Access system - updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList); + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, epRequestValue); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); } // In case if portal is not centralized then follow existing approach @@ -882,7 +879,7 @@ public class UserRolesCommonServiceImpl { remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService); if (remoteAppUser == null) { - addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService); + remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService); } if (remoteAppUser != null) { Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, @@ -913,143 +910,151 @@ public class UserRolesCommonServiceImpl { } return result; } - + /** + * It adds user roles in External system and also make data consistent in both local and in External System + * + * @param app details + * @param orgUserId + * @param roleInAppUser Contains list of active roles + */ @SuppressWarnings("unchecked") - private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser) - { - try{ - //check if user exists - final Map<String, String> userParams = new HashMap<>(); - userParams.put("orgUserIdValue", orgUserId); - List<EPUser> userInfo = checkIfUserExists(userParams); - if (userInfo.size() == 0 || userInfo.isEmpty()) { - createLocalUserIfNecessary(orgUserId); - } - final Map<String, String> loginIdParams = new HashMap<>(); - loginIdParams.put("orgUserIdValue", orgUserId); - EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0); - String name = ""; - if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { - name = orgUserId - + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); - } - ObjectMapper mapper = new ObjectMapper(); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth() ; - HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); - ResponseEntity<String> getResponse = template - .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); - if(getResponse.getStatusCode().value() == 200){ - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to external system and received user roles: ", getResponse.getBody()); + private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) + { + try { + // check if user exists + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", orgUserId); + List<EPUser> userInfo = checkIfUserExists(userParams); + if (userInfo.isEmpty()) { + createLocalUserIfNecessary(orgUserId); + } + String name = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = orgUserId + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity<String> getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); + if (getResponse.getStatusCode().value() == 200) { + logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}", + getResponse.getBody()); - } - List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>(); - String res = getResponse.getBody(); - JSONObject jsonObj = null; - JSONArray extRoles = null; - if (!res.equals("{}")) { - jsonObj = new JSONObject(res); - extRoles = jsonObj.getJSONArray("role"); - } - ExternalAccessUserRoleDetail userRoleDetail = null; - if (extRoles != null) { - for (int i = 0; i < extRoles.length(); i++) { - if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".") && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace()+".admin") - && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace()+".owner")) { - ObjectMapper descMapper = new ObjectMapper(); - if(extRoles.getJSONObject(i).has("description")){ - ExternalRoleDescription desc = descMapper.readValue( - extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class); - userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"), - desc); - userRoleDetailList.add(userRoleDetail); - }else{ - userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"), - null); - userRoleDetailList.add(userRoleDetail); - } + } + List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>(); + String res = getResponse.getBody(); + JSONObject jsonObj = null; + JSONArray extRoles = null; + if (!res.equals("{}")) { + jsonObj = new JSONObject(res); + extRoles = jsonObj.getJSONArray("role"); + } + ExternalAccessUserRoleDetail userRoleDetail = null; + if (extRoles != null) { + for (int i = 0; i < extRoles.length(); i++) { + if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".") + && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin") + && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) { + ObjectMapper descMapper = new ObjectMapper(); + if (extRoles.getJSONObject(i).has("description")) { + ExternalRoleDescription desc = descMapper.readValue( + extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class); + userRoleDetail = new ExternalAccessUserRoleDetail( + extRoles.getJSONObject(i).getString("name"), desc); + userRoleDetailList.add(userRoleDetail); + } else { + userRoleDetail = new ExternalAccessUserRoleDetail( + extRoles.getJSONObject(i).getString("name"), null); + userRoleDetailList.add(userRoleDetail); + } + } } } - } - for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) { - HttpEntity<String> entity = new HttpEntity<>(headers); - template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "userRole/" + name + "/" + userRole.getName(), HttpMethod.DELETE, entity, String.class); - } - final Map<String, RoleInAppForUser> roleInAppUserMap = new HashMap<>(); - for(RoleInAppForUser roleInAppUserNew: roleInAppUser){ - roleInAppUserMap.put(roleInAppUserNew.getRoleName(), roleInAppUserNew); - } - final Map<String, Long> params = new HashMap<>(); - params.put("appId", app.getId()); - params.put("userId", user.getId()); - List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", params, null); - // Check if incoming request has sys admin or account admin, if exists add in external system - if (!roleInAppUser.isEmpty()) { - for (EcompUserAppRoles userApp : userAppList) { - if ((userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID) - || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !roleInAppUserMap.containsKey(userApp.getRoleName())) { - RoleInAppForUser addSpecialRole = new RoleInAppForUser(); - addSpecialRole.setIsApplied(true); - addSpecialRole.setRoleId(userApp.getRoleId()); - addSpecialRole.setRoleName(userApp.getRoleName()); - roleInAppUser.add(addSpecialRole); + // If request coming from portal not from external role approval system then we have to check if user already + // have account admin or system admin as GUI will not send these roles + if (!isPortalRequest) { + final Map<String, String> loginIdParams = new HashMap<>(); + loginIdParams.put("orgUserIdValue", orgUserId); + EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0); + final Map<String, Long> params = new HashMap<>(); + params.put("appId", app.getId()); + params.put("userId", user.getId()); + List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", + params, null); + if (!roleInAppUser.isEmpty()) { + for (EcompUserAppRoles userApp : userAppList) { + if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID) + || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) { + RoleInAppForUser addSpecialRole = new RoleInAppForUser(); + addSpecialRole.setIsApplied(true); + addSpecialRole.setRoleId(userApp.getRoleId()); + addSpecialRole.setRoleName(userApp.getRoleName()); + roleInAppUser.add(addSpecialRole); + } } } } - List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct().collect(Collectors.toList()); - for (RoleInAppForUser addRole : roleInAppUserNonDupls) { - ExternalAccessUser extUser = null; - if ((addRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) - && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - try{ - String extRole = app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ","_"); - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - ResponseEntity<String> getRoleResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"+extRole, - HttpMethod.GET, entity, String.class); - String extAdminRole = app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); - if(getRoleResponse.getBody().equals("{}")){ - String addDesc = "{\"name\":\"" +extAdminRole+ "\"}"; - HttpEntity<String> roleEntity = new HttpEntity<>(addDesc,headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", - HttpMethod.POST, roleEntity, String.class); - } - extUser = new ExternalAccessUser(name, - app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_")); - } catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to add admin role for application {} ",app.getId(),e); - continue; + List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct() + .collect(Collectors.toList()); + final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>(); + for (RoleInAppForUser roleInAppUserNew : roleInAppUser) { + currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName(), roleInAppUserNew); + } + final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>(); + for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleDetailList) { + currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole); + } + // Check if roles does not exists in local but still there in External Central Auth System delete them all + for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) { + if (!(currentUserRolesToUpdate + .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1).replaceAll("_", " ")) + || currentUserRolesToUpdate + .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) { + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}", + userRole); + ResponseEntity<String> deleteResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + userRole.getName(), + HttpMethod.DELETE, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}", + userRole, deleteResponse.getBody()); } - } else { - extUser = new ExternalAccessUser(name, - app.getNameSpace() + "." + addRole.getRoleName().replaceAll(" ", "_")); } - // Assign user role for an application in external access system - String userRole = mapper.writeValueAsString(extUser); - HttpEntity<String> entity = new HttpEntity<>(userRole, headers); - if (addRole.getIsApplied()) { - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system and adding user role", - addRole.getRoleName()); - ResponseEntity<String> addResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", - HttpMethod.POST, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to external system and added user role", - getResponse.getBody(), addRole.getRoleName()); - if (addResponse.getStatusCode().value() != 201) { + // Check if user roles does not exists in External Central Auth System add them all + for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) { + if (!(currentUserRolesInExternalSystem + .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_")))) { + ExternalAccessUser extUser = new ExternalAccessUser(name, + app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_")); + String formattedUserRole = mapper.writeValueAsString(extUser); + HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system and adding user role", + addUserRole.getRoleName()); + ResponseEntity<String> addResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole", HttpMethod.POST, entity, String.class); logger.debug(EELFLoggerDelegate.debugLogger, - "Connected to external system unable to save user role", getResponse.getBody(), - addRole.getRoleName()); - throw new Exception("Failed to add user role for application"); + "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}", + getResponse.getBody(), addUserRole.getRoleName()); + if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Finished POST operation in external system but unable to save user role", getResponse.getBody(), + addUserRole.getRoleName()); + throw new Exception(addResponse.getBody()); + } } } - } - }catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user role for application {}", app.getId(),e); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e); } } @@ -1270,20 +1275,22 @@ public class UserRolesCommonServiceImpl { .executeNamedQuery("userAppRolesRequestList", params, null); epRequestIdSize = epRequestId.size(); } + + //If Non-Centralized app make sure you sync app roles before assigning to user if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()){ EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles"); syncAppRoles(sessionFactory, app.getId(), appRoles); } - List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(), app.getId(), app.getMlAppName()); List<EcompUserAppRoles> userRoleList = null; - if(userId != null){ + if(!userInfo.isEmpty()){ final Map<String, Long> appParams = new HashMap<>(); appParams.put("userId", userId.getId()); appParams.put("appId", app.getId()); userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null); } + // Check if list contains just account admin role boolean checkIfAdminRoleExists = false; if (reqType.equals("DELETE")) { checkIfAdminRoleExists = userRoleList.stream() @@ -1296,8 +1303,9 @@ public class UserRolesCommonServiceImpl { if (app.getCentralAuth()) { // We should add If user does not exist in remote application try { - if (!(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && checkIfAdminRoleExists - && (roleInAppForUserList.size() == 1 || reqType.equals("DELETE")))) { + // If adding just account admin role dont make remote application user call + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists + && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) { EPUser remoteAppUser = null; remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, applicationsRestClientService); @@ -1309,7 +1317,7 @@ public class UserRolesCommonServiceImpl { } } catch (Exception e) { reqMessage = e.getMessage(); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to added remote user", e); + logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e); throw new Exception(reqMessage); } Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, @@ -1318,8 +1326,8 @@ public class UserRolesCommonServiceImpl { userRolesInLocalApp); List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles; // Apply changes in external Access system - updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList); - logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", logMessage, + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest); + logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); } @@ -1331,12 +1339,12 @@ public class UserRolesCommonServiceImpl { userRolesInLocalApp); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); } else {// remote app - + // If adding just account admin role don't do remote application user call if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){ EPUser remoteAppUser = null; remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, applicationsRestClientService); if (remoteAppUser == null) { - addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService); + remoteAppUser = addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService); reqMessage = "Saved Successfully"; } if (remoteAppUser != null) { @@ -1345,7 +1353,7 @@ public class UserRolesCommonServiceImpl { RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInRemoteApp); - logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", + logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, @@ -1361,14 +1369,15 @@ public class UserRolesCommonServiceImpl { }*/ } } else { - if(!(reqType.equals("DELETE") && userId == null)){ + // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote + if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){ reqMessage = "Saved Successfully"; } Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInRemoteApp); - logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", + logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); @@ -1382,7 +1391,7 @@ public class UserRolesCommonServiceImpl { } } } catch (Exception e) { - String message = String.format("Failed to create user or update user roles for User %s, AppId %s", + String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s", orgUserId, appName); logger.error(EELFLoggerDelegate.errorLogger, message, e); result = false; @@ -1545,6 +1554,8 @@ public class UserRolesCommonServiceImpl { EcompRole[] appRoles = null; List<EcompRole> roles = new ArrayList<>(); if(app.getCentralAuth()){ + //Sync application roles from External Access System + externalAccessRolesService.syncApplicationRolesWithEcompDB(app); List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);; for(EPRole role : applicationRoles){ EcompRole ecompRole = new EcompRole(); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java index 0284452a..f29f9d91 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java @@ -414,4 +414,14 @@ public class EcompPortalUtils { return result; } + public static String truncateString(String originString, int size){ + if(originString.length()>=size){ + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(originString); + stringBuilder.setLength(size); + stringBuilder.append("..."); + return stringBuilder.toString(); + } + return originString; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java index 57bb543f..56bb542a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java @@ -27,4 +27,5 @@ public interface PortalConstants { public static final Long SYS_ADMIN_ROLE_ID = 1L; public static final String ADMIN_ROLE = "Account Administrator"; public static final String PORTAL_ADMIN_ROLE = "System Administrator"; + public static final Integer AUDIT_LOG_COMMENT_SIZE = 990; } diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml index 342a6e8c..1574a9a2 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml @@ -1911,9 +1911,12 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y <return alias="getUserRolesListForLeftMenu" class="org.openecomp.portalapp.portal.domain.UserRole" /> <![CDATA[ - - SELECT DISTINCT user.USER_ID, role.ROLE_ID, user.org_user_id, user.FIRST_NAME, user.LAST_NAME, role.ROLE_NAME FROM fn_user_role userrole INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID INNER JOIN fn_role role ON role.ROLE_ID = userrole.ROLE_ID WHERE user.org_user_id =:org_user_id and (userrole.app_id = 1 or role.role_id = 999) - ; + SELECT DISTINCT user.USER_ID, role.ROLE_ID, user.org_user_id, user.FIRST_NAME, user.LAST_NAME, role.ROLE_NAME FROM fn_user_role userrole + INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID + INNER JOIN fn_app app ON app.app_id= userrole.app_id + INNER JOIN fn_role role ON role.ROLE_ID = userrole.ROLE_ID + WHERE user.org_user_id =:org_user_id and (userrole.app_id = 1 or role.role_id = 999) and (app.enabled='Y' or app.app_id=1) + ; ]]> </sql-query> diff --git a/ecomp-portal-BE-os/pom.xml b/ecomp-portal-BE-os/pom.xml index 22b13749..00e77c20 100644 --- a/ecomp-portal-BE-os/pom.xml +++ b/ecomp-portal-BE-os/pom.xml @@ -7,63 +7,50 @@ <version>1.1</version> <properties> + <portal.version>1.3.0-SNAPSHOT</portal.version> + <epsdk.version>1.3.0</epsdk.version> + <!-- Jenkins SHOULD invoke mvn with argument -Dbuild.number=${BUILD_NUMBER} --> + <build.number>0</build.number> <springframework.version>4.2.0.RELEASE</springframework.version> <hibernate.version>4.3.11.Final</hibernate.version> <eelf.version>1.0.0</eelf.version> - <epsdk.version>1.3.0-SNAPSHOT</epsdk.version> - <portal.version>1.3.0-SNAPSHOT</portal.version> <encoding>UTF-8</encoding> - <!-- If Skiptests is false use mvn clean jacoco:prepare-agent install jacoco:report - to run jacoco report --> + <!-- If skipTests is false use this command to generate the report: + mvn clean jacoco:prepare-agent install jacoco:report --> <skipTests>false</skipTests> <skipCoverage>true</skipCoverage> - <!-- Jenkins SHOULD invoke mvn with argument -Dbuild.number=${BUILD_NUMBER} --> - <build.number>0</build.number> + <jacoco.data.file>${project.build.directory}/coverage-reports/jacoco-ut.exec</jacoco.data.file> + <sonar-jacoco-listeners.version>3.8</sonar-jacoco-listeners.version> + <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin> + <sonar.jacoco.reportPath>${project.build.directory}/code-coverage/jacoco.exec</sonar.jacoco.reportPath> + <sonar.jacoco.itReportPath>${project.build.directory}/code-coverage/jacoco-it.exec</sonar.jacoco.itReportPath> + <!-- Note: This list should match jacoco-maven-plugin's exclusion list below --> <sonar.exclusions>**.js</sonar.exclusions> <nexusproxy>https://nexus.onap.org</nexusproxy> <snapshotNexusPath>content/repositories/snapshots/</snapshotNexusPath> + <stagingNexusPath>content/repositories/staging/</stagingNexusPath> <releaseNexusPath>content/repositories/releases/</releaseNexusPath> </properties> - <reporting> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - <version>2.10.4</version> - <configuration> - <failOnError>false</failOnError> - <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> - <docletArtifact> - <groupId>org.umlgraph</groupId> - <artifactId>umlgraph</artifactId> - <version>5.6</version> - </docletArtifact> - <additionalparam>-views</additionalparam> - <useStandardDocletOptions>true</useStandardDocletOptions> - </configuration> - </plugin> - - </plugins> - </reporting> - <distributionManagement> - <site> - <id>ecomp-site</id> - <url>dav:${nexusproxy}/content/sites/site/org/onap/portal/${project.version}</url> - </site> - </distributionManagement> <repositories> <repository> <id>onap-releases</id> + <name>ONAP - Release Repository</name> <url>${nexusproxy}/${releaseNexusPath}</url> </repository> <repository> + <id>onap-staging</id> + <name>ONAP - Staging Repository</name> + <url>${nexusproxy}/${stagingNexusPath}</url> + </repository> + <repository> <id>onap-snapshots</id> + <name>ONAP - Snapshot Repository</name> <url>${nexusproxy}/${snapshotNexusPath}</url> </repository> <repository> <id>onap-public</id> - <url>https://nexus.onap.org/content/groups/public</url> + <url>${nexusproxy}/content/groups/public</url> </repository> </repositories> @@ -98,28 +85,25 @@ <target>1.8</target> </configuration> </plugin> - <plugin> + <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.5.201505241946</version> <executions> - <!-- Prepares the property pointing to the JaCoCo runtime agent which - is passed as VM argument when Maven the Surefire plugin is executed. --> + is passed as VM argument when Maven the Surefire plugin is executed. --> <execution> <id>pre-unit-test</id> <goals> <goal>prepare-agent</goal> </goals> <configuration> - <!-- Sets the path to the file which contains the execution data. --> - <destFile>${basedir}/target/coverage-reports/jacoco-ut.exec</destFile> - <!-- Sets the name of the property containing the settings for JaCoCo - runtime agent. --> + <!-- path to the file which contains the execution data. --> + <destFile>${jacoco.data.file}</destFile> + <!-- name of the property containing the settings for JaCoCo runtime agent. --> <propertyName>surefireArgLine</propertyName> <skip>${skipCoverage}</skip> </configuration> - </execution> <!-- Ensures that the code coverage report for unit tests is created after unit tests have been run. --> @@ -130,12 +114,11 @@ <goal>report</goal> </goals> <configuration> - <!-- Sets the path to the file which contains the execution data. --> - <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile> - <!-- Sets the output directory for the code coverage report. --> + <!-- path to the file which contains the execution data. --> + <dataFile>${jacoco.data.file}</dataFile> + <!-- output directory for the code coverage report. --> <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory> <skip>${skipCoverage}</skip> - </configuration> </execution> <!-- Will see build errors while running the test cases because of dual @@ -800,4 +783,34 @@ </dependency> </dependencies> + + <reporting> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.10.4</version> + <configuration> + <failOnError>false</failOnError> + <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> + <docletArtifact> + <groupId>org.umlgraph</groupId> + <artifactId>umlgraph</artifactId> + <version>5.6</version> + </docletArtifact> + <additionalparam>-views</additionalparam> + <useStandardDocletOptions>true</useStandardDocletOptions> + </configuration> + </plugin> + + </plugins> + </reporting> + + <distributionManagement> + <site> + <id>ecomp-site</id> + <url>dav:${nexusproxy}/content/sites/site/org/onap/portal/${project.version}</url> + </site> + </distributionManagement> + </project> diff --git a/ecomp-portal-FE-common/README.md b/ecomp-portal-FE-common/README.md index c4ac1e87..e69e32aa 100644 --- a/ecomp-portal-FE-common/README.md +++ b/ecomp-portal-FE-common/README.md @@ -8,8 +8,6 @@ of the ECOMP Portal web application. Those specific versions are built using separate Maven projects that copy in ("overlay") the contents of this project at package time. -## Static files +Release Notes -Static files should be entered into the ecomp-portal-FE-common/home directory, -whereby home = the webserver html root directory. The files and directories -will be copied exactly as they are placed. + - PORTAL-86 remove "home" subdirectory with static files diff --git a/ecomp-portal-FE-common/client/app/router.js b/ecomp-portal-FE-common/client/app/router.js index 190ed579..7a3d3a71 100644 --- a/ecomp-portal-FE-common/client/app/router.js +++ b/ecomp-portal-FE-common/client/app/router.js @@ -241,7 +241,7 @@ angular.module('ecompApp') url: '/error404', views: { 'content@': { - templateUrl: 'app/views/errors/error.404.tpl.html', + templateUrl: 'app/views/errors/error.tpl.html', controller: 'ErrorCtrl', controllerAs: 'error' } diff --git a/ecomp-portal-FE-common/client/app/views/errors/error.controller.js b/ecomp-portal-FE-common/client/app/views/errors/error.controller.js new file mode 100644 index 00000000..5f4f410d --- /dev/null +++ b/ecomp-portal-FE-common/client/app/views/errors/error.controller.js @@ -0,0 +1,20 @@ +'use strict'; +(function () { + class ErrorCtrl { + constructor($log, $scope,$state) { + $scope.errorState = $state.current.name; + if($scope.errorState=='root.error404'){ + $scope.errorTitle="Page Not Found"; + $scope.errorMsg="The page you are looking for cannot be found"; + }else if($scope.errorState=='noUserError'){ + $scope.errorTitle="Authorization denied"; + $scope.errorMsg= "Please Contact Your Administrator for the page access"; + }else { + $scope.errorTitle="Something went wrong"; + $scope.errorMsg= "Please go back to the previous page"; + } + } + } + ErrorCtrl.$inject = ['$log','$scope','$state']; + angular.module('ecompApp').controller('ErrorCtrl', ErrorCtrl); +})();
\ No newline at end of file diff --git a/ecomp-portal-FE-common/client/app/views/errors/error.tpl.html b/ecomp-portal-FE-common/client/app/views/errors/error.tpl.html new file mode 100644 index 00000000..44b43ce4 --- /dev/null +++ b/ecomp-portal-FE-common/client/app/views/errors/error.tpl.html @@ -0,0 +1,31 @@ +<!-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --> +<div class="w-ecomp-admins-page-main"> + <div id="page-content"> + <div id="title" class="w-ecomp-main-view-title"> + <h1 class="heading-page">{{errorTitle}}</h1> + </div> + <div class="errorContent"> + <p>{{errorMsg}}</p> + </div> + + </div> + +</div> diff --git a/ecomp-portal-FE-common/client/app/views/role/role.html b/ecomp-portal-FE-common/client/app/views/role/role.html index 9febc978..63073aeb 100644 --- a/ecomp-portal-FE-common/client/app/views/role/role.html +++ b/ecomp-portal-FE-common/client/app/views/role/role.html @@ -94,30 +94,7 @@ </div> <a id="manage-role" href="roleFunctions">Manage Role Functions</a><br><br> - - <div id="page-title-child" class="pageTitle"> - <label>Child Roles</label> - <a id="add-child-role" ng-click="addNewChildRoleModalPopup();" ng-style="{'cursor':'pointer'}" class="icon-primary-accordion-plus" size="small"></a> - </div> - - <div b2b-table table-data="role.childRoles" ng-hide="users.isLoadingTable" search-string="users.searchString" class="b2b-table-div"> - <table> - <thead b2b-table-row type="header"> - <tr > - <th id="table-header-name" b2b-table-header key="firstName" sortable="true" >Name</th> - <th id="table-header-remove" b2b-table-header key="lastName" sortable="true" >Remove</th> - </tr> - </thead> - <tbody b2b-table-row type="body" row-repeat="role in role.childRoles"> - <tr > - <td id="role-function-{{role.name}}" b2b-table-body id="rowheader_t1_{{$index}}" headers="col1" ng-bind="role.name"></td> - <td b2b-table-body headers="rowheader_t1_{{$index}} col4" id="{{$index}}-button-remove-role" > - <div ng-click="removeChildRole(role);" ><a href="javascript:void(0)" class="icon-misc-trash"></a></div> - </td> - </tr> - </tbody> - </table> - </div> + </div> </div> </div> diff --git a/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.controller.js b/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.controller.js index 48f7d9df..366fb215 100644 --- a/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.controller.js +++ b/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.controller.js @@ -19,11 +19,11 @@ */ 'use strict'; -(function () { +(function() { class userNotificationsModalCtrl { - constructor($scope, $log, functionalMenuService, confirmBoxService, notificationService, $modal, ngDialog, $state, $filter,items) { - this.debug = false; + constructor($scope, $log, functionalMenuService, confirmBoxService, notificationService, $modal, ngDialog, $state, $filter, items) { + this.debug = false; $scope.newNotifModel = { 'isOnlineUsersOnly': null, 'isForAllRolesOptions': null, @@ -34,10 +34,12 @@ 'msgHeader': null, 'msgDescription': null, 'roleIds': null, - 'anyTreeItemSelected':false, - 'roleObj': {notificationRoleIds:null} + 'anyTreeItemSelected': false, + 'roleObj': { + notificationRoleIds: null + } }; - + $scope.notificationId = null; $scope.selectedCat = null; $scope.selectedEcompFunc = null; @@ -45,42 +47,72 @@ "Y": 0, "N": 1 } - - $scope.onlineAllUsersOptions = [ - { "index": 0, "value": "Y", "title": "Online Users Only" }, - { "index": 1, "value": "N", "title": "Online & Offline Users" } - + + $scope.onlineAllUsersOptions = [{ + "index": 0, + "value": "Y", + "title": "Online Users Only" + }, + { + "index": 1, + "value": "N", + "title": "Online & Offline Users" + } + ]; - $scope.isForAllRolesOptions = [ - { "index": 0, "value": "Y", "title": "Yes" }, - { "index": 1, "value": "N", "title": "No" } + $scope.isForAllRolesOptions = [{ + "index": 0, + "value": "Y", + "title": "Yes" + }, + { + "index": 1, + "value": "N", + "title": "No" + } ]; - $scope.priorityOptions = [ - { "index": 0, "value": 1, "title": "Normal" }, - { "index": 1, "value": 2, "title": "Important" } + $scope.priorityOptions = [{ + "index": 0, + "value": 1, + "title": "Normal" + }, + { + "index": 1, + "value": 2, + "title": "Important" + } ]; - $scope.isActiveOptions = [ - { "index": 0, "value": "Y", "title": "Yes" }, - { "index": 1, "value": "N", "title": "No" } + $scope.isActiveOptions = [{ + "index": 0, + "value": "Y", + "title": "Yes" + }, + { + "index": 1, + "value": "N", + "title": "No" + } ]; $scope.newNotifModel.isActive = $scope.isActiveOptions[0]; $scope.newNotifModel.selectPriority = $scope.priorityOptions[0]; $scope.newNotifModel.isOnlineUsersOnly = $scope.onlineAllUsersOptions[1]; - $scope.newNotifModel.isForAllRoles=$scope.isForAllRolesOptions[0].value; - $scope.newNotifModel.isFunctionalMenu ="Y"; - - $scope.newNotifModel.selectedPriority=$scope.priorityOptions[0].value; - $scope.newNotifModel.msgHeader = ''; - $scope.newNotifModel.msgDescription = ''; - $scope.newNotifModel.treeTitle="Functional Menu"; - $scope.newNotifModel.notifObj= {isCategoriesFunctionalMenu:true}; + $scope.newNotifModel.isForAllRoles = $scope.isForAllRolesOptions[0].value; + $scope.newNotifModel.isFunctionalMenu = "Y"; + + $scope.newNotifModel.selectedPriority = $scope.priorityOptions[0].value; + $scope.newNotifModel.msgHeader = ''; + $scope.newNotifModel.msgDescription = ''; + $scope.newNotifModel.treeTitle = "Functional Menu"; + $scope.newNotifModel.notifObj = { + isCategoriesFunctionalMenu: true + }; let init = () => { - if(this.debug) - $log.debug('userNotificationsModalCtrl::init'); + if (this.debug) + $log.debug('userNotificationsModalCtrl::init'); this.isSaving = false; var today = new Date(); $scope.minDate = today.toISOString().substring(0, 10); @@ -88,10 +120,12 @@ threeMonthsFromNow.setMonth(threeMonthsFromNow.getMonth() + 3); $scope.maxDate = threeMonthsFromNow.toISOString().substring(0, 10); if (items && items.notif) { - if(this.debug) - $log.debug('userNotificationsModalCtrl:init:: Edit notification mode for', items.notif); + if (this.debug) + $log.debug('userNotificationsModalCtrl:init:: Edit notification mode for', items.notif); $scope.isEditMode = true; - $scope.editModeObj = {isEditMode: true}; + $scope.editModeObj = { + isEditMode: true + }; this.notif = _.clone(items.notif); $scope.modalPgTitle = 'View Notification' $scope.newNotifModel.isOnlineUsersOnly = $scope.onlineAllUsersOptions[this.YN_index_mapping[this.notif.isForOnlineUsers]]; @@ -104,24 +138,30 @@ $scope.newNotifModel.msgDescription = this.notif.msgDescription; $scope.notificationId = this.notif.notificationId; $scope.newNotifModel.notificationRoleIds = this.notif.roleIds; - $scope.roleObj = {notificationRoleIds:this.notif.roleIds}; + $scope.roleObj = { + notificationRoleIds: this.notif.roleIds + }; } else { - if(this.debug) - $log.debug('AppDetailsModalCtrl:init:: New app mode'); + if (this.debug) + $log.debug('AppDetailsModalCtrl:init:: New app mode'); $scope.isEditMode = false; - $scope.editModeObj = {isEditMode: false}; + $scope.editModeObj = { + isEditMode: false + }; $scope.modalPgTitle = 'Add a New Notification' this.notif = _.clone($scope.newNotifModel); - $scope.roleObj = {notificationRoleIds:null}; + $scope.roleObj = { + notificationRoleIds: null + }; } }; this.conflictMessages = {}; this.scrollApi = {}; let handleConflictErrors = err => { - if(!err.data){ + if (!err.data) { return; } - if(!err.data.length){ // support objects + if (!err.data.length) { // support objects err.data = [err.data] } _.forEach(err.data, item => { @@ -139,42 +179,66 @@ let resetConflict = fieldName => { delete this.conflictMessages[fieldName]; - if($scope.appForm[fieldName]){ + if ($scope.appForm[fieldName]) { $scope.appForm[fieldName].$setValidity('conflict', true); } }; - $scope.addUserNotificationValidation = function () { - // // pre-processing - if (!($scope.isEditMode)) { - var validation=false; - if($scope.isDateValid($scope.newNotifModel.startTime) && $scope.isDateValid($scope.newNotifModel.endTime) && $scope.newNotifModel.msgHeader != '' && $scope.newNotifModel.msgDescription != '' && ($scope.newNotifModel.startTime<$scope.newNotifModel.endTime)){ - validation=true; - if( $scope.newNotifModel.isForAllRoles=='N'){ - validation = $scope.checkTreeSelect(); - } - } - else{ - validation=false; - } - return !validation; - } - } - + $scope.addUserNotificationValidation = function() { + // // pre-processing + if (!($scope.isEditMode)) { + var validation = false; + if ($scope.isStartDateValidFromToday($scope.newNotifModel.startTime)&&$scope.isStartDateValidFromToday($scope.newNotifModel.endTime)&&$scope.isDateValid($scope.newNotifModel.startTime) && $scope.isDateValid($scope.newNotifModel.endTime) && $scope.newNotifModel.msgHeader != '' && $scope.newNotifModel.msgDescription != '' && ($scope.newNotifModel.startTime < $scope.newNotifModel.endTime)) { + validation = true; + if ($scope.newNotifModel.isForAllRoles == 'N') { + validation = $scope.checkTreeSelect(); + } + } else { + validation = false; + } + return !validation; + } + } + /* format the value for viewing a notification */ - $scope.formatStartDate = function () { - if ($scope.newNotifModel.startTime) { - $scope.newNotifModel.startTime = $filter('date')($scope.startTime, 'medium'); - } + $scope.formatStartDate = function() { + if ($scope.newNotifModel.startTime) { + $scope.newNotifModel.startTime = $filter('date')($scope.startTime, 'medium'); + } } - + /* format the value for viewing a notification */ - $scope.formatEndDate = function () { - if($scope.newNotifModel.endTime){ - $scope.newNotifModel.endTime = $filter('date')($scope.endTime, 'medium'); - } + $scope.formatEndDate = function() { + if ($scope.newNotifModel.endTime) { + $scope.newNotifModel.endTime = $filter('date')($scope.endTime, 'medium'); + } } - $scope.isDateValid = function (time) { + /*To validate the manual entry of date in MM/DD/YYYY Format*/ + + $scope.isDateValid = function(time) { + if (time == undefined) { + return false; + } + if (typeof time == 'object') { + return true; + } + var startDateformat = time.split('/'); + if (startDateformat.length != 3) return false; + var day = startDateformat[1]; + var month = startDateformat[0]; + month = parseInt(month) - 1; + var year = startDateformat[2]; + if (year.length != 4) return false; + var composedDate = new Date(year, month, day); + return composedDate.getDate() == day && + composedDate.getMonth() == month && + composedDate.getFullYear() == year; + }; + + /*The manual and drop down calendar should be consistent. + Start date must be greater than or equal to current date.The end dates are not allowed after the 3 months from current dates*/ + + $scope.isStartDateValidFromToday = function (time) { if(time == undefined){ return false; } @@ -182,309 +246,317 @@ return true; } var startDateformat =time.split('/'); - if (startDateformat.length != 3) return false; + if (startDateformat.length != 3) return true; var day = startDateformat[1]; var month = startDateformat[0]; month= parseInt(month)-1; var year = startDateformat[2]; - if(year.length!=4) return false; + if(year.length!=4) return true; var composedDate = new Date(year, month, day); - return composedDate.getDate() == day && - composedDate.getMonth() == month && - composedDate.getFullYear() == year; - + /* As end dates are not allowed after the 3 months from current dates*/ + var x = 3; //or whatever offset + var CurrentDate = new Date(); + /*If composed date is less than the current date,error message should display*/ + if(composedDate<CurrentDate) + return false; + CurrentDate.setMonth(CurrentDate.getMonth() + x); + if(composedDate>CurrentDate) + return false; + return true; }; - - - $scope.addUserNotification = function () { - $scope.notificationRoleIds = []; - // pre-processing - - for(var fi=0;fi<$scope.treedata.length;fi++){ - var fLevel = $scope.treedata[fi]; - if(fLevel){ - var fLevelChild = fLevel.child; - for(var si=0;si<fLevelChild.length;si++){ - var sLevel = fLevelChild[si]; - if(sLevel){ - var sLevelChild = sLevel.child; - if(sLevelChild){ - for(var ti=0;ti< sLevelChild.length;ti++){ - var tLevel = sLevelChild[ti]; - if(tLevel.isSelected && tLevel.roleId){ - $scope.newNotifModel.anyTreeItemSelected=true; - for(var i in tLevel.roleId) - $scope.notificationRoleIds.push(tLevel.roleId[i]); - } - } - } - } - if(sLevel.isSelected && sLevel.roleId){ - for(var i in sLevel.roleId) - $scope.notificationRoleIds.push(sLevel.roleId[i]); - } - } - } - } - - $scope.notificationRoleIds.sort(); - if (($scope.newNotifModel.isOnlineUsersOnly) && ($scope.newNotifModel.isForAllRoles) && ($scope.newNotifModel.selectedPriority) && ($scope.newNotifModel.isActive) - && ($scope.newNotifModel.startTime) && ($scope.newNotifModel.endTime) && ($scope.newNotifModel.msgHeader != '') && ($scope.newNotifModel.msgDescription != '')) { - this.newUserNotification = - { - 'notificationId':$scope.notificationId, - 'isForOnlineUsers': $scope.newNotifModel.isOnlineUsersOnly.value, - 'isForAllRoles': $scope.newNotifModel.isForAllRoles, - 'priority': $scope.newNotifModel.selectedPriority, - 'activeYn': $scope.newNotifModel.isActive.value, - 'startTime': $scope.newNotifModel.startTime, - 'endTime': $scope.newNotifModel.endTime, - 'msgHeader': $scope.newNotifModel.msgHeader, - 'msgDescription': $scope.newNotifModel.msgDescription, - 'roleIds': $scope.notificationRoleIds, - 'createdDate': new Date() - }; - - // POST ajax call here; - if ($scope.isEditMode) { - notificationService.updateAdminNotification(this.newUserNotification) - .then(() => { - if(this.debug) - $log.debug('NotificationService:updateAdminNotification:: Admin notification update succeeded!'); - $scope.closeThisDialog(true); - }).catch(err => { - $log.error('notificationService.updateAdminNotfication failed: ' + JSON.stringify(err)); - switch (err.status) { - case '409': // Conflict - // handleConflictErrors(err); - break; - case '500': // Internal Server Error - confirmBoxService.showInformation('There was a problem updating the notification. ' + - 'Please try again later. Error: ' + err.status).then(isConfirmed => { }); - break; - case '403': // Forbidden... possible - // webjunction error to - // try again - confirmBoxService.showInformation('There was a problem updating the notification. ' + - 'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => { }); - break; - default: - confirmBoxService.showInformation('There was a problem updating the notification. ' + - 'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => { }); - } - }).finally(() => { - // for bug in IE 11 - var objOffsetVersion = objAgent.indexOf("MSIE"); - if (objOffsetVersion != -1) { - if(this.debug) - $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: Browser is IE, forcing Refresh'); - $window.location.reload(); - } - // for bug in IE 11 - }); - - } else { - notificationService.addAdminNotification(this.newUserNotification) - .then((res) => { - if(this.debug) - $log.debug('notificationService:addAdminNotification:: Admin notification creation succeeded!,',res); - if(res.status=='ERROR'){ - confirmBoxService.showInformation('There was a problem adding the notification. ' + - ' Error: ' + res.response).then(isConfirmed => { }); - - - } - else{ - //$scope.closeThisDialog(true); - $scope.$dismiss('cancel'); - } - - // emptyCookies(); - }).catch(err => { - switch (err.status) { - case '409': // Conflict - // handleConflictErrors(err); - break; - case '500': // Internal Server Error - confirmBoxService.showInformation('There was a problem adding the notification. ' + - 'Please try again later. Error: ' + err.status).then(isConfirmed => { }); - break; - default: - confirmBoxService.showInformation('There was a problem adding the notification. ' + - 'Please try again. If the problem persists, then try again later. Error: ' + - err.status).then(isConfirmed => { }); - } - $log.error('notificationService:addAdminNotification error:: ' + JSON.stringify(err)); - }) - } - - - } else { - $log.warn('please fill in all required fields'); - confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => { }); - } + + + $scope.addUserNotification = function() { + $scope.notificationRoleIds = []; + // pre-processing + + for (var fi = 0; fi < $scope.treedata.length; fi++) { + var fLevel = $scope.treedata[fi]; + if (fLevel) { + var fLevelChild = fLevel.child; + if (fLevelChild) { + for (var si = 0; si < fLevelChild.length; si++) { + var sLevel = fLevelChild[si]; + if (sLevel) { + var sLevelChild = sLevel.child; + if (sLevelChild) { + for (var ti = 0; ti < sLevelChild.length; ti++) { + var tLevel = sLevelChild[ti]; + if (tLevel.isSelected && tLevel.roleId) { + $scope.newNotifModel.anyTreeItemSelected = true; + for (var i in tLevel.roleId) + $scope.notificationRoleIds.push(tLevel.roleId[i]); + } + } + } + } + if (sLevel.isSelected && sLevel.roleId) { + for (var i in sLevel.roleId) + $scope.notificationRoleIds.push(sLevel.roleId[i]); + } + } + } + } + } + + $scope.notificationRoleIds.sort(); + if (($scope.newNotifModel.isOnlineUsersOnly) && ($scope.newNotifModel.isForAllRoles) && ($scope.newNotifModel.selectedPriority) && ($scope.newNotifModel.isActive) && + ($scope.newNotifModel.startTime) && ($scope.newNotifModel.endTime) && ($scope.newNotifModel.msgHeader != '') && ($scope.newNotifModel.msgDescription != '')) { + this.newUserNotification = { + 'notificationId': $scope.notificationId, + 'isForOnlineUsers': $scope.newNotifModel.isOnlineUsersOnly.value, + 'isForAllRoles': $scope.newNotifModel.isForAllRoles, + 'priority': $scope.newNotifModel.selectedPriority, + 'activeYn': $scope.newNotifModel.isActive.value, + 'startTime': $scope.newNotifModel.startTime, + 'endTime': $scope.newNotifModel.endTime, + 'msgHeader': $scope.newNotifModel.msgHeader, + 'msgDescription': $scope.newNotifModel.msgDescription, + 'roleIds': $scope.notificationRoleIds, + 'createdDate': new Date() + }; + + // POST ajax call here; + if ($scope.isEditMode) { + notificationService.updateAdminNotification(this.newUserNotification) + .then(() => { + if (this.debug) + $log.debug('NotificationService:updateAdminNotification:: Admin notification update succeeded!'); + $scope.closeThisDialog(true); + }).catch(err => { + $log.error('notificationService.updateAdminNotfication failed: ' + JSON.stringify(err)); + switch (err.status) { + case '409': // Conflict + // handleConflictErrors(err); + break; + case '500': // Internal Server Error + confirmBoxService.showInformation('There was a problem updating the notification. ' + + 'Please try again later. Error: ' + err.status).then(isConfirmed => {}); + break; + case '403': // Forbidden... possible + // webjunction error to + // try again + confirmBoxService.showInformation('There was a problem updating the notification. ' + + 'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {}); + break; + default: + confirmBoxService.showInformation('There was a problem updating the notification. ' + + 'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {}); + } + }).finally(() => { + // for bug in IE 11 + var objOffsetVersion = objAgent.indexOf("MSIE"); + if (objOffsetVersion != -1) { + if (this.debug) + $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: Browser is IE, forcing Refresh'); + $window.location.reload(); + } + // for bug in IE 11 + }); + + } else { + notificationService.addAdminNotification(this.newUserNotification) + .then((res) => { + if (this.debug) + $log.debug('notificationService:addAdminNotification:: Admin notification creation succeeded!,', res); + if (res.status == 'ERROR') { + confirmBoxService.showInformation('There was a problem adding the notification. ' + + ' Error: ' + res.response).then(isConfirmed => {}); + + + } else { + // $scope.closeThisDialog(true); + $scope.$dismiss('cancel'); + } + + // emptyCookies(); + }).catch(err => { + switch (err.status) { + case '409': // Conflict + // handleConflictErrors(err); + break; + case '500': // Internal Server Error + confirmBoxService.showInformation('There was a problem adding the notification. ' + + 'Please try again later. Error: ' + err.status).then(isConfirmed => {}); + break; + default: + confirmBoxService.showInformation('There was a problem adding the notification. ' + + 'Please try again. If the problem persists, then try again later. Error: ' + + err.status).then(isConfirmed => {}); + } + $log.error('notificationService:addAdminNotification error:: ' + JSON.stringify(err)); + }) + } + + + } else { + $log.warn('please fill in all required fields'); + confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {}); + } + } + $scope.functionalMenuRes = {}; + $scope.checkTreeSelect = function() { + if ($scope.treedata) { + for (var fi = 0; fi < $scope.treedata.length; fi++) { + var fLevel = $scope.treedata[fi]; + if (fLevel.isSelected) { + return true; + } + var sLevel = fLevel.child; + if (sLevel) { + for (var si = 0; si < sLevel.length; si++) { + if (sLevel[si].isSelected) { + return true; + } + var tLevel = sLevel[si].child; + if (tLevel) { + for (var ti = 0; ti < tLevel.length; ti++) { + if (tLevel[ti].isSelected) { + return true; + } + } + } + } + } + } + } + return false; } - $scope.functionalMenuRes={}; - $scope.checkTreeSelect = function(){ - if($scope.treedata){ - for(var fi=0; fi<$scope.treedata.length;fi++){ - var fLevel = $scope.treedata[fi]; - if(fLevel.isSelected){ - return true; - } - var sLevel = fLevel.child; - if(sLevel){ - for(var si=0;si<sLevel.length;si++){ - if(sLevel[si].isSelected){ - return true; - } - var tLevel = sLevel[si].child; - if(tLevel){ - for(var ti=0;ti<tLevel.length;ti++){ - if(tLevel[ti].isSelected){ - return true; - } - } - } - } - } - } - } - return false; - } // Populate the category list for category dropdown list let getFunctionalMenu = () => { - this.isLoadingTable = true; - if(this.debug) - $log.debug('getFunctionalMenu:init'); - - functionalMenuService.getFunctionalMenuRole().then(role_res => { - var menu_role_dict = {}; - if(this.debug) - $log.debug('functionalMenuService:getFunctionalMenuRole:: getting result', role_res); - - for (var i in role_res) { - // if first time appear in menu_role_dict - if (!(role_res[i].menuId in menu_role_dict)) { - menu_role_dict[role_res[i].menuId] = [role_res[i].roleId]; - } else { - menu_role_dict[role_res[i].menuId].push(role_res[i].roleId); - } - } - - functionalMenuService.getManagedFunctionalMenuForNotificationTree().then(res => { - if(this.debug) - $log.debug('functionalMenuService:getManagedFunctionalMenuForNotificationTree:: getting result', res); - var exclude_list = ['Favorites']; - let actualData=[]; - $scope.functionalMenuRes=res; - - //Adding children and label attribute to all objects in res - for(let i = 0; i < res.length; i++){ - res[i].child=[]; - res[i].name=res[i].text; - res[i].id=res[i].text; - res[i].displayCheckbox= true; - $scope.checkBoxObj = {isAnyRoleSelected:false}; - res[i].roleId = menu_role_dict[res[i].menuId]; - res[i].onSelect = function () { - $scope.$apply(function () { - $scope.newNotifModel.anyTreeItemSelected=$scope.checkTreeSelect(); - }) - }; - - if (res[i].roleId && res[i].roleId.length==_.intersection(res[i].roleId, $scope.roleObj.notificationRoleIds).length){ - res[i].isSelected= true; - res[i].selected= true; - res[i].indeterminate= false; - }else{ - /*default*/ - res[i].isSelected= false; - res[i].selected= false; - res[i].indeterminate= false; - } - } - - // Adding actual child items to children array in res - // objects - $scope.parentChildDict ={}; - $scope.parentChildRoleIdDict ={}; - for (let i = 0; i < res.length; i++) { - let parentId = res[i].menuId; - $scope.parentChildDict[parentId] = []; - $scope.parentChildRoleIdDict[parentId]=[]; - for (let j = 0; j < res.length; j++) { - let childId = res[j].parentMenuId; - if (parentId === childId) { - res[i].child.push(res[j]); - $scope.parentChildDict[parentId].push(res[j].menuId); - //if res[j].roleId is defined - if (res[j].roleId) { - for (let k in res[j].roleId) { - $scope.parentChildRoleIdDict[parentId].push(res[j].roleId[k]); - } - - } - } - } - } - //check if grand children exist - for (var key in $scope.parentChildDict){ - var child = $scope.parentChildDict[key]; - var isGrandParent = false; - if (child.length>0) { - for (var i in child) { - if ($scope.parentChildDict[child[i]].length>0){ - isGrandParent = true; - break; - } - } - } - if (isGrandParent) { - for (var i in child) { - // if the child has children - if ($scope.parentChildDict[child[i]].length>0) { - for (var j in $scope.parentChildRoleIdDict[child[i]]) { - if ($scope.parentChildRoleIdDict[key].indexOf($scope.parentChildRoleIdDict[child[i]][j]) === -1) { - $scope.parentChildRoleIdDict[key].push($scope.parentChildRoleIdDict[child[i]][j]); - } - } - } - } - } - - }; - - // Sort the top-level menu items in order based on the column - res.sort(function(a, b) { - return a.column-b.column; - }); - - // Sort all the child in order based on the column - for(let i = 0; i < res.length; i++){ - res[i].child.sort(function(a, b){ - return a.column-b.column; - }); - } - - //Forming actual parent items - for(let i = 0; i < res.length; i++){ - let parentId=res[i].parentMenuId; - if(parentId===null){ - actualData.push(res[i]); - } - } - var treedata = actualData[0].child; - $scope.treedata = []; - - /*Remove favorite from the list */ - for (var i in treedata) { - if (!(treedata[i].name.indexOf(exclude_list) > -1)) { - $scope.treedata.push(treedata[i]) - } - } - //setting b2b tree parameter - $scope.settingTreeParam(); + this.isLoadingTable = true; + if (this.debug) + $log.debug('getFunctionalMenu:init'); + + functionalMenuService.getFunctionalMenuRole().then(role_res => { + var menu_role_dict = {}; + if (this.debug) + $log.debug('functionalMenuService:getFunctionalMenuRole:: getting result', role_res); + + for (var i in role_res) { + // if first time appear in menu_role_dict + if (!(role_res[i].menuId in menu_role_dict)) { + menu_role_dict[role_res[i].menuId] = [role_res[i].roleId]; + } else { + menu_role_dict[role_res[i].menuId].push(role_res[i].roleId); + } + } + + functionalMenuService.getManagedFunctionalMenuForNotificationTree().then(res => { + if (this.debug) + $log.debug('functionalMenuService:getManagedFunctionalMenuForNotificationTree:: getting result', res); + var exclude_list = ['Favorites']; + let actualData = []; + $scope.functionalMenuRes = res; + + //Adding children and label attribute to all objects in res + for (let i = 0; i < res.length; i++) { + res[i].child = []; + res[i].name = res[i].text; + res[i].id = res[i].text; + res[i].displayCheckbox = true; + $scope.checkBoxObj = { + isAnyRoleSelected: false + }; + res[i].roleId = menu_role_dict[res[i].menuId]; + res[i].onSelect = function() { + $scope.$apply(function() { + $scope.newNotifModel.anyTreeItemSelected = $scope.checkTreeSelect(); + }) + }; + + if (res[i].roleId && res[i].roleId.length == _.intersection(res[i].roleId, $scope.roleObj.notificationRoleIds).length) { + res[i].isSelected = true; + res[i].selected = true; + res[i].indeterminate = false; + } else { + /*default*/ + res[i].isSelected = false; + res[i].selected = false; + res[i].indeterminate = false; + } + } + + // Adding actual child items to children array in res + // objects + $scope.parentChildDict = {}; + $scope.parentChildRoleIdDict = {}; + for (let i = 0; i < res.length; i++) { + let parentId = res[i].menuId; + $scope.parentChildDict[parentId] = []; + $scope.parentChildRoleIdDict[parentId] = []; + for (let j = 0; j < res.length; j++) { + let childId = res[j].parentMenuId; + if (parentId === childId) { + res[i].child.push(res[j]); + $scope.parentChildDict[parentId].push(res[j].menuId); + //if res[j].roleId is defined + if (res[j].roleId) { + for (let k in res[j].roleId) { + $scope.parentChildRoleIdDict[parentId].push(res[j].roleId[k]); + } + + } + } + } + } + //check if grand children exist + for (var key in $scope.parentChildDict) { + var child = $scope.parentChildDict[key]; + var isGrandParent = false; + if (child.length > 0) { + for (var i in child) { + if ($scope.parentChildDict[child[i]].length > 0) { + isGrandParent = true; + break; + } + } + } + if (isGrandParent) { + for (var i in child) { + // if the child has children + if ($scope.parentChildDict[child[i]].length > 0) { + for (var j in $scope.parentChildRoleIdDict[child[i]]) { + if ($scope.parentChildRoleIdDict[key].indexOf($scope.parentChildRoleIdDict[child[i]][j]) === -1) { + $scope.parentChildRoleIdDict[key].push($scope.parentChildRoleIdDict[child[i]][j]); + } + } + } + } + } + + }; + + // Sort the top-level menu items in order based on the column + res.sort(function(a, b) { + return a.column - b.column; + }); + + // Sort all the child in order based on the column + for (let i = 0; i < res.length; i++) { + res[i].child.sort(function(a, b) { + return a.column - b.column; + }); + } + + //Forming actual parent items + for (let i = 0; i < res.length; i++) { + let parentId = res[i].parentMenuId; + if (parentId === null) { + actualData.push(res[i]); + } + } + var treedata = actualData[0].child; + $scope.treedata = []; + + /*Remove favorite from the list */ + for (var i in treedata) { + if (!(treedata[i].name.indexOf(exclude_list) > -1)) { + $scope.treedata.push(treedata[i]) + } + } + //setting b2b tree parameter + $scope.settingTreeParam(); }).catch(err => { $log.error('FunctionalMenuCtrl:getFunctionalMenu:: error ', err); @@ -494,244 +566,247 @@ }).catch(err => { $log.error('FunctionalMenuCtrl:getFunctionalMenu:: error ', err); - }) - ; + }); } - - + + let getAppRoleIds = () => { - $scope.notifObj= {isCategoriesFunctionalMenu:false}; - notificationService.getAppRoleIds().then(res => { - if(this.debug) - $log.debug('notificationService:getAppRoleIds:: getting result', res); - res = res.data; - let actualData = []; - var app_id_name_list = {}; - $scope.checkBoxObj = {isAnyRoleSelected:false}; - for (let i = 0; i < res.length; i++) { - if (!(res[i].appId in app_id_name_list)) { - app_id_name_list[res[i].appId] = res[i].appName; - } - res[i].child=[]; - res[i].name=res[i].roleName; - res[i].displayCheckbox= true; - res[i].id = res[i].roleId; - res[i].menuId = res[i].roleId; - res[i].parentMenuId = res[i].appId; - res[i].can_check = true; - res[i].roleId = [res[i].roleId]; - res[i].onSelect = function () { - $scope.$apply(function () { - $scope.newNotifModel.anyTreeItemSelected=$scope.checkTreeSelect(); - }) - }; - /*assigning selected value*/ - if (res[i].roleId && res[i].roleId.length==_.intersection(res[i].roleId, $scope.roleObj.notificationRoleIds).length){ - res[i].isSelected= true; - res[i].selected= true; - res[i].indeterminate= false; - }else{ - /*default*/ - res[i].isSelected= false; - res[i].selected= false; - res[i].indeterminate= false; - } - } - - for (var app_id in app_id_name_list) { - var new_res = {}; - new_res.child = []; - new_res.name = app_id_name_list[app_id]; - new_res.id = app_id; - new_res.displayCheckbox= true; - new_res.menuId = app_id; - new_res.parentMenuId = null; - new_res.appId = null; - new_res.can_check = true; - new_res.roleId = null; - new_res.onSelect = function () { - $scope.$apply(function () { - $scope.newNotifModel.anyTreeItemSelected=$scope.checkTreeSelect(); - }) - }; - res.push(new_res); - } - $scope.parentChildRoleIdDict ={}; - //Adding actual child items to child array in res objects - for (let i = 0; i < res.length; i++) { - let parentId = res[i].menuId; - $scope.parentChildRoleIdDict[parentId]=[]; - for (let j = 0; j < res.length; j++) { - let childId = res[j].parentMenuId; - if (parentId == childId) { - res[i].child.push(res[j]); - if (res[j].roleId) { - for (let k in res[j].roleId) { - $scope.parentChildRoleIdDict[parentId].push(res[j].roleId[k]); - } - - } - } - } - } - //Forming actual parent items - for (let i = 0; i < res.length; i++) { - let parentId = res[i].parentMenuId; - if (parentId === null) { - actualData.push(res[i]); - } - } - - $scope.treedata = actualData; - //setting correct parameters for b2b tree - $scope.settingTreeParam(); + $scope.notifObj = { + isCategoriesFunctionalMenu: false + }; + notificationService.getAppRoleIds().then(res => { + if (this.debug) + $log.debug('notificationService:getAppRoleIds:: getting result', res); + res = res.data; + let actualData = []; + var app_id_name_list = {}; + $scope.checkBoxObj = { + isAnyRoleSelected: false + }; + for (let i = 0; i < res.length; i++) { + if (!(res[i].appId in app_id_name_list)) { + app_id_name_list[res[i].appId] = res[i].appName; + } + res[i].child = []; + res[i].name = res[i].roleName; + res[i].displayCheckbox = true; + res[i].id = res[i].roleId; + res[i].menuId = res[i].roleId; + res[i].parentMenuId = res[i].appId; + res[i].can_check = true; + res[i].roleId = [res[i].roleId]; + res[i].onSelect = function() { + $scope.$apply(function() { + $scope.newNotifModel.anyTreeItemSelected = $scope.checkTreeSelect(); + }) + }; + /*assigning selected value*/ + if (res[i].roleId && res[i].roleId.length == _.intersection(res[i].roleId, $scope.roleObj.notificationRoleIds).length) { + res[i].isSelected = true; + res[i].selected = true; + res[i].indeterminate = false; + } else { + /*default*/ + res[i].isSelected = false; + res[i].selected = false; + res[i].indeterminate = false; + } + } + + for (var app_id in app_id_name_list) { + var new_res = {}; + new_res.child = []; + new_res.name = app_id_name_list[app_id]; + new_res.id = app_id; + new_res.displayCheckbox = true; + new_res.menuId = app_id; + new_res.parentMenuId = null; + new_res.appId = null; + new_res.can_check = true; + new_res.roleId = null; + new_res.onSelect = function() { + $scope.$apply(function() { + $scope.newNotifModel.anyTreeItemSelected = $scope.checkTreeSelect(); + }) + }; + res.push(new_res); + } + $scope.parentChildRoleIdDict = {}; + //Adding actual child items to child array in res objects + for (let i = 0; i < res.length; i++) { + let parentId = res[i].menuId; + $scope.parentChildRoleIdDict[parentId] = []; + for (let j = 0; j < res.length; j++) { + let childId = res[j].parentMenuId; + if (parentId == childId) { + res[i].child.push(res[j]); + if (res[j].roleId) { + for (let k in res[j].roleId) { + $scope.parentChildRoleIdDict[parentId].push(res[j].roleId[k]); + } + + } + } + } + } + //Forming actual parent items + for (let i = 0; i < res.length; i++) { + let parentId = res[i].parentMenuId; + if (parentId === null) { + actualData.push(res[i]); + } + } + + $scope.treedata = actualData; + //setting correct parameters for b2b tree + $scope.settingTreeParam(); }).catch(err => { $log.error('FunctionalMenuCtrl:getFunctionalMenu:: error ', err); }).finally(() => { this.isLoadingTable = false; }) } - $scope.getFunctionalMenu= function() { - $scope.treeTitle="Functional Menu"; - getFunctionalMenu(); + $scope.getFunctionalMenu = function() { + $scope.treeTitle = "Functional Menu"; + getFunctionalMenu(); } $scope.getAppRoleIds = function() { - $scope.treeTitle="Applications/Roles"; + $scope.treeTitle = "Applications/Roles"; getAppRoleIds(); } - - - - $scope.settingTreeParam = function(){ - /**************first level****************/ - for(var fi=0; fi<$scope.treedata.length;fi++){ - var fLevel = $scope.treedata[fi]; - var sLevel = $scope.treedata[fi].child; - var sLevelSelectedCount =0; - var sLevelChildNumber =0 - if(fLevel.child.length==0 && fLevel.roleId==null){ - delete fLevel.child; - }else if(sLevel){ - /**************Second level****************/ - var sLevelDelArray=[]; - for(var si=0;si<sLevel.length;si++){ - var deletThisSLev= false; - if(sLevel[si].child.length==0 && sLevel[si].roleId==null){ - sLevel[si].displayCheckbox=false; - sLevelDelArray.push(sLevel[si].name); - sLevel[si].name = ''; - sLevel[si].active=false; - delete sLevel[si].child; - } else if(sLevel[si].child.length==0){ - delete sLevel[si].child; - }else{ - /**************Third level****************/ - var tLevel = sLevel[si].child; - var tLevelSelectedCount =0; - var tLevelChildNumber =0; - if(tLevel){ - var tLevelDelArray=[]; - var tLevelLen = tLevel.length; - var tLevelRoleIdUndefined =0; - for(var ti=0;ti<tLevel.length;ti++){ - delete tLevel[ti].child; - if(tLevel[ti].roleId==null){ - tLevel[ti].displayCheckbox=false; - tLevelDelArray.push(tLevel[ti].name); - tLevel[ti].name = ''; - tLevel[ti].active=false; - tLevelRoleIdUndefined++ - }else{ - if(tLevel[ti].isSelected) - tLevelSelectedCount++; - - if(tLevel[ti].displayCheckbox) - tLevelChildNumber++; - } - } - if(tLevelRoleIdUndefined==tLevelLen) - deletThisSLev=true; - if(tLevelSelectedCount==tLevelChildNumber){ - sLevel[si].isSelected=true; - sLevel[si].indeterminate=false; - sLevel[si].active=true; - }else if(tLevelSelectedCount>0){ - sLevel[si].indeterminate=true; - sLevel[si].active=true; - } - - /*Cleanup unused third level items*/ - for(var i=0;i<tLevelDelArray.length;i++){ - var name = tLevelDelArray[i]; - for(var ti=0;ti<tLevel.length;ti++){ - if(name==tLevel[ti].text){ - tLevel.splice(ti,1); - break; - } - } - } - } - } - if(deletThisSLev){ //remove the whole second level item if all it's child has no roleId - sLevel[si].displayCheckbox=false; - sLevelDelArray.push(sLevel[si].name); - sLevel[si].name = ''; - sLevel[si].active=false; - }else{ - if(sLevel[si].isSelected) - sLevelSelectedCount++; - if(sLevel[si].displayCheckbox) - sLevelChildNumber++; - } - } - if(sLevelSelectedCount==sLevelChildNumber && sLevelChildNumber!=0){ - fLevel.isSelected=true; - fLevel.indeterminate=false; - fLevel.active=true; - }else if(sLevelSelectedCount>0){ - fLevel.indeterminate=true; - fLevel.active=true; - }else{ - //fLevel.active=false; - fLevel.indeterminate=false; - } - /*Cleanup unused second level items*/ - for(var i=0;i<sLevelDelArray.length;i++){ - var name = sLevelDelArray[i]; - for(var si=0;si<sLevel.length;si++){ - if(name==sLevel[si].text){ - sLevel.splice(si,1); - break; - } - } - } - } - } + + + + $scope.settingTreeParam = function() { + /**************first level****************/ + for (var fi = 0; fi < $scope.treedata.length; fi++) { + var fLevel = $scope.treedata[fi]; + var sLevel = $scope.treedata[fi].child; + var sLevelSelectedCount = 0; + var sLevelChildNumber = 0 + if (fLevel.child.length == 0 && fLevel.roleId == null) { + delete fLevel.child; + } else if (sLevel) { + /**************Second level****************/ + var sLevelDelArray = []; + for (var si = 0; si < sLevel.length; si++) { + var deletThisSLev = false; + if (sLevel[si].child.length == 0 && sLevel[si].roleId == null) { + sLevel[si].displayCheckbox = false; + sLevelDelArray.push(sLevel[si].name); + sLevel[si].name = ''; + sLevel[si].active = false; + delete sLevel[si].child; + } else if (sLevel[si].child.length == 0) { + delete sLevel[si].child; + } else { + /**************Third level****************/ + var tLevel = sLevel[si].child; + var tLevelSelectedCount = 0; + var tLevelChildNumber = 0; + if (tLevel) { + var tLevelDelArray = []; + var tLevelLen = tLevel.length; + var tLevelRoleIdUndefined = 0; + for (var ti = 0; ti < tLevel.length; ti++) { + delete tLevel[ti].child; + if (tLevel[ti].roleId == null) { + tLevel[ti].displayCheckbox = false; + tLevelDelArray.push(tLevel[ti].name); + tLevel[ti].name = ''; + tLevel[ti].active = false; + tLevelRoleIdUndefined++ + } else { + if (tLevel[ti].isSelected) + tLevelSelectedCount++; + + if (tLevel[ti].displayCheckbox) + tLevelChildNumber++; + } + } + if (tLevelRoleIdUndefined == tLevelLen) + deletThisSLev = true; + if (tLevelSelectedCount == tLevelChildNumber) { + sLevel[si].isSelected = true; + sLevel[si].indeterminate = false; + sLevel[si].active = true; + } else if (tLevelSelectedCount > 0) { + sLevel[si].indeterminate = true; + sLevel[si].active = true; + } + + /*Cleanup unused third level items*/ + for (var i = 0; i < tLevelDelArray.length; i++) { + var name = tLevelDelArray[i]; + for (var ti = 0; ti < tLevel.length; ti++) { + if (name == tLevel[ti].text) { + tLevel.splice(ti, 1); + break; + } + } + } + } + } + if (deletThisSLev) { //remove the whole second level item if all it's child has no roleId + sLevel[si].displayCheckbox = false; + sLevelDelArray.push(sLevel[si].name); + sLevel[si].name = ''; + sLevel[si].active = false; + } else { + if (sLevel[si].isSelected) + sLevelSelectedCount++; + if (sLevel[si].displayCheckbox) + sLevelChildNumber++; + } + } + if (sLevelSelectedCount == sLevelChildNumber && sLevelChildNumber != 0) { + fLevel.isSelected = true; + fLevel.indeterminate = false; + fLevel.active = true; + } else if (sLevelSelectedCount > 0) { + fLevel.indeterminate = true; + fLevel.active = true; + } else { + //fLevel.active=false; + fLevel.indeterminate = false; + } + /*Cleanup unused second level items*/ + for (var i = 0; i < sLevelDelArray.length; i++) { + var name = sLevelDelArray[i]; + for (var si = 0; si < sLevel.length; si++) { + if (name == sLevel[si].text) { + sLevel.splice(si, 1); + break; + } + } + } + } + } } init(); getFunctionalMenu(); } - + } - - userNotificationsModalCtrl.$inject = ['$scope', '$log', 'functionalMenuService', 'confirmBoxService', 'notificationService', '$modal', 'ngDialog', '$state', '$filter','items']; + + userNotificationsModalCtrl.$inject = ['$scope', '$log', 'functionalMenuService', 'confirmBoxService', 'notificationService', '$modal', 'ngDialog', '$state', '$filter', 'items']; angular.module('ecompApp').controller('userNotificationsModalCtrl', userNotificationsModalCtrl); - + angular.module('ecompApp').directive('attDatepickerCustom', ['$log', function($log) { return { restrict: 'A', - require: 'ngModel', + require: 'ngModel', scope: {}, - + controller: ['$scope', '$element', '$attrs', '$compile', 'datepickerConfig', 'datepickerService', function($scope, $element, $attrs, $compile, datepickerConfig, datepickerService) { - var dateFormatString = angular.isDefined($attrs.dateFormat) ? $scope.$parent.$eval($attrs.dateFormat) : datepickerConfig.dateFormat; - var selectedDateMessage = '<div class="sr-focus hidden-spoken" tabindex="-1">the date you selected is {{$parent.current | date : \'' + dateFormatString + '\'}}</div>'; - $element.removeAttr('att-datepicker-custom'); + var dateFormatString = angular.isDefined($attrs.dateFormat) ? $scope.$parent.$eval($attrs.dateFormat) : datepickerConfig.dateFormat; + var selectedDateMessage = '<div class="sr-focus hidden-spoken" tabindex="-1">the date you selected is {{$parent.current | date : \'' + dateFormatString + '\'}}</div>'; + $element.removeAttr('att-datepicker-custom'); $element.removeAttr('ng-model'); $element.attr('ng-value', '$parent.current | date:"EEEE, MMMM d, y"'); $element.attr('aria-describedby', 'datepicker'); - + $element.attr('maxlength', 10); var wrapperElement = angular.element('<div></div>'); @@ -763,10 +838,10 @@ ctrl.$render = function() { scope.current = ctrl.$viewValue; }; - + } }; }]); - -})(); + +})();
\ No newline at end of file diff --git a/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.less b/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.less index 79c2bae2..17bbdab8 100644 --- a/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.less +++ b/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.less @@ -169,3 +169,16 @@ right: 10px; top: 8px; } + +.date-validation{ + top:185px; + color: #cf2a2a; + font-size: 10px; + position:absolute; +} +.endDate-validation{ + top:270px; + color: #cf2a2a; + font-size: 10px; + position:absolute; +}
\ No newline at end of file diff --git a/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.page.html b/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.page.html index 57433c1c..5d1698e5 100644 --- a/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.page.html +++ b/ecomp-portal-FE-common/client/app/views/user-notifications-admin/user.notifications.modal.page.html @@ -131,10 +131,14 @@ ng-model="newNotifModel.startTime" b2b-datepicker min="minDate" max="maxDate" required /> </div> - <div id="user-startdate-required" ng-show="!isDateValid(newNotifModel.startTime)"> - <small class="mandatory-categories">Please enter valid date in MM/DD/YYYY format!</small> + <div style="{{( isEditMode )? 'opacity : 0; pointer-events: none;':' '}}"> + <div id="user-startdate-required" ng-show="!isDateValid(newNotifModel.startTime)"> + <small class="mandatory-categories">Please enter valid date in MM/DD/YYYY format!</small> + </div> + <div id="user-startdate-required" ng-show="!isStartDateValidFromToday(newNotifModel.startTime)"> + <small class="date-validation">Date should be greater than or equal to current date!</small> + </div> </div> - </div> <div ng-show="!isEditMode" ng-init="formatStartDate()"></div> </div> @@ -142,18 +146,23 @@ <div id="add-user-notif-enddate" class="add-widget-field" style="padding-bottom: 12px; width: 301px !important; {{( isEditMode )? 'opacity : 0.6; pointer-events: none;':' '}}"> <div id="user-notification-enddate-label" class="user-notif-label"> - <span runat="server" ID="required" class="notifcation-label-user-requiredId">*</span> End Date (Local Time) + <span runat="server" ID="required" class="notifcation-label-user-requiredId">*</span> EndDate (Local Time) </div> <div class="datepicker-container"> <input class="notif-input-calendar" type="text" id="datepicker-end" ng-model="newNotifModel.endTime" b2b-datepicker min="minDate" max="maxDate" required /> </div> - <div id="user-endDate-required" ng-show="!isDateValid(newNotifModel.endTime)"> + <div style="{{( isEditMode )? 'opacity : 0; pointer-events: none;':' '}}"> + <div id="user-endDate-required" ng-show="!isDateValid(newNotifModel.endTime)"> <small class="mandatory-categories">Please enter valid date in MM/DD/YYYY format!</small> </div> - <div id="user-enddate-error" ng-show="newNotifModel.endTime&&newNotifModel.startTime&&newNotifModel.startTime.getTime()>=newNotifModel.endTime.getTime()" class="user-enddate-error-txt"> - <small class="mandatory-categories">End Date must be greater than start Date</small> + <div id="user-startdate-required" ng-show="!isStartDateValidFromToday(newNotifModel.endTime)"> + <small class="endDate-validation">Date should be greater than or equal to current date!</small> + </div> + <div id="user-enddate-error" ng-show="newNotifModel.endTime&&newNotifModel.startTime&&newNotifModel.startTime.getTime()>=newNotifModel.endTime.getTime()" class="user-enddate-error-txt"> + <small class="mandatory-categories">End Date must be greater than start Date</small> + </div> </div> <div ng-show="!isEditMode" ng-init="formatEndDate()" ></div> </div> @@ -181,7 +190,7 @@ ng-model="newNotifModel.msgDescription" name="content"> </textarea> <div id="user-notif-message-required" ng-show="newNotifModel.msgDescription.length ==0 "> - <small class="mandatory-categories">Message is Required</small> + <small class="mandatory-categories">Message is Required</small> </div> </div> diff --git a/ecomp-portal-FE-common/client/app/views/widget-onboarding/widget-onboarding.less b/ecomp-portal-FE-common/client/app/views/widget-onboarding/widget-onboarding.less index 6085a908..7be0d470 100644 --- a/ecomp-portal-FE-common/client/app/views/widget-onboarding/widget-onboarding.less +++ b/ecomp-portal-FE-common/client/app/views/widget-onboarding/widget-onboarding.less @@ -34,5 +34,8 @@ font-style: italic; { margin-bottom: 8px; } +input.table-search{ + font-style: normal; +} } diff --git a/ecomp-portal-FE-common/client/app/views/widget-onboarding/widget-onboarding.tpl.html b/ecomp-portal-FE-common/client/app/views/widget-onboarding/widget-onboarding.tpl.html index aae0fd7c..aeb4468c 100644 --- a/ecomp-portal-FE-common/client/app/views/widget-onboarding/widget-onboarding.tpl.html +++ b/ecomp-portal-FE-common/client/app/views/widget-onboarding/widget-onboarding.tpl.html @@ -36,10 +36,10 @@ </select> </div> </div> - <input class="table-search" type="text" + <input class="table-search" type="text" id="widget-onboarding-table-search" placeholder="Search in entire table" - ng-model="widgetOnboarding.searchString" /> + data-ng-model="widgetOnboarding.searchString" /> <button id="widget-onboarding-button-add" class="btn btn-alt btn-small" @@ -55,7 +55,7 @@ <div ng-hide="widgetOnboarding.isCommError"> <div b2b-table table-data="portalAdmin.portalAdminsTableData" ng-hide="widgetOnboarding.isLoadingTable" - search-string="portalAdmin.searchString" class="b2b-table-div"> + search-string="widgetOnboarding.searchString" class="b2b-table-div"> <table> <thead b2b-table-row type="header"> <tr> diff --git a/ecomp-portal-FE-common/home/ecompportal/applicationsHome b/ecomp-portal-FE-common/home/ecompportal/applicationsHome deleted file mode 100644 index e2a981e4..00000000 --- a/ecomp-portal-FE-common/home/ecompportal/applicationsHome +++ /dev/null @@ -1,9 +0,0 @@ -<html> -<body> -ECOMP Portal has moved to this new location <a href="https://www.e-access.att.com/ecomp_portal/"> https://www.e-access.att.com/ecomp_portal/ </a> -<p> -Please update your bookmarks. -</p> -</body> -</html> - diff --git a/ecomp-portal-FE-common/home/ecompportal/login.htm b/ecomp-portal-FE-common/home/ecompportal/login.htm deleted file mode 100644 index e2a981e4..00000000 --- a/ecomp-portal-FE-common/home/ecompportal/login.htm +++ /dev/null @@ -1,9 +0,0 @@ -<html> -<body> -ECOMP Portal has moved to this new location <a href="https://www.e-access.att.com/ecomp_portal/"> https://www.e-access.att.com/ecomp_portal/ </a> -<p> -Please update your bookmarks. -</p> -</body> -</html> - diff --git a/ecomp-portal-FE-common/home/index.html b/ecomp-portal-FE-common/home/index.html deleted file mode 100644 index 5e433099..00000000 --- a/ecomp-portal-FE-common/home/index.html +++ /dev/null @@ -1,3 +0,0 @@ -<script> -window.location.href = "ecompui/login.htm" -</script> diff --git a/ecomp-portal-FE-os/client/src/app.less b/ecomp-portal-FE-os/client/src/app.less index 6e7df2a4..bf7a96e5 100644 --- a/ecomp-portal-FE-os/client/src/app.less +++ b/ecomp-portal-FE-os/client/src/app.less @@ -92,4 +92,9 @@ body { z-index: 100; display: none; opacity: 0; +} + +.errorContent p{ + font-size: 28px; + margin-left: 120px; }
\ No newline at end of file diff --git a/ecomp-portal-FE-os/pom.xml b/ecomp-portal-FE-os/pom.xml index aa853498..ae3921ad 100644 --- a/ecomp-portal-FE-os/pom.xml +++ b/ecomp-portal-FE-os/pom.xml @@ -22,8 +22,17 @@ <directory>${basedir}/client/app</directory> </fileset> <fileset> + <directory>${basedir}/dist</directory> + </fileset> + <fileset> <directory>${basedir}/.tmp</directory> </fileset> + <fileset> + <directory>${basedir}/node</directory> + </fileset> + <fileset> + <directory>${basedir}/node_modules</directory> + </fileset> </filesets> </configuration> </plugin> diff --git a/ecomp-portal-widget-ms/common-widgets/pom.xml b/ecomp-portal-widget-ms/common-widgets/pom.xml index a71c5ac5..6a6d54bd 100644 --- a/ecomp-portal-widget-ms/common-widgets/pom.xml +++ b/ecomp-portal-widget-ms/common-widgets/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.openecomp.portal</groupId> - <artifactId>widget-ms-widgets-os</artifactId> + <artifactId>common-widgets</artifactId> <version>1.3.0-SNAPSHOT</version> <packaging>pom</packaging> diff --git a/ecomp-portal-widget-ms/widget-ms/pom.xml b/ecomp-portal-widget-ms/widget-ms/pom.xml index dcab5721..b421ebd5 100644 --- a/ecomp-portal-widget-ms/widget-ms/pom.xml +++ b/ecomp-portal-widget-ms/widget-ms/pom.xml @@ -25,6 +25,13 @@ </properties> <dependencies> + <!-- This pom pulls in artifacts --> + <dependency> + <groupId>org.openecomp.portal</groupId> + <artifactId>common-widgets</artifactId> + <version>${project.version}</version> + <type>pom</type> + </dependency> <dependency> <!-- Setup Spring Data JPA Repository support --> <groupId>org.springframework.boot</groupId> @@ -6,6 +6,7 @@ <artifactId>ecompportal-parent-project</artifactId> <version>0</version> <packaging>pom</packaging> + <name>portal</name> <modules> <!-- Child modules do NOT name this parent. --> |