diff options
author | Manoop Talasila <talasila@research.att.com> | 2020-01-31 15:31:56 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2020-01-31 15:31:56 +0000 |
commit | 728c55e4233b5f7e449f67dea4c4ca987da701b7 (patch) | |
tree | d8e64cd335f6b1fb8d62d514e61a626b389ef2f4 /portal-BE | |
parent | e363b25a09970065499f91e9b54be0149517e737 (diff) | |
parent | 77cf3af4adc17b6c83250819bbe944eeacbb61c4 (diff) |
Merge changes I68af4999,I2fb38f2a,Ia11ca8d2,I36b83288,I129c127c, ...
* changes:
SchedulerAuxController up
SchedulerController up
SharedContextRestController up
TicketEventVersionController up
UserNotificationController up
PersUserWidgetServiceAOP and tests up
Removing attached entity from method argument
Diffstat (limited to 'portal-BE')
71 files changed, 6674 insertions, 1834 deletions
diff --git a/portal-BE/build.sh b/portal-BE/build.sh index 2d1a4426..10398e2c 100755 --- a/portal-BE/build.sh +++ b/portal-BE/build.sh @@ -2,7 +2,9 @@ export spring_datasource_username=portal export spring_datasource_password=Test123456 - -mvn clean install +echo "mvn clean install" +mvn clean install > file-log.log +echo "docker build" docker build -t portal_app . -docker-compose up
\ No newline at end of file +echo "docker compose" +docker-compose up diff --git a/portal-BE/pom.xml b/portal-BE/pom.xml index 94340971..77336be7 100644 --- a/portal-BE/pom.xml +++ b/portal-BE/pom.xml @@ -158,6 +158,24 @@ <version>1.5.13</version> <scope>compile</scope> </dependency> + <dependency> + <groupId>org.glassfish.jersey.core</groupId> + <artifactId>jersey-client</artifactId> + <version>2.29.1</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.eclipse.jetty</groupId> + <artifactId>jetty-util</artifactId> + <version>9.4.18.v20190429</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.jaxrs</groupId> + <artifactId>jackson-jaxrs-json-provider</artifactId> + <version>2.10.0</version> + <scope>compile</scope> + </dependency> </dependencies> <properties> <docker.image.prefix>portal</docker.image.prefix> diff --git a/portal-BE/src/main/java/org/onap/portal/aop/service/PersUserWidgetServiceAOP.java b/portal-BE/src/main/java/org/onap/portal/aop/service/PersUserWidgetServiceAOP.java index 79326618..904e0704 100644 --- a/portal-BE/src/main/java/org/onap/portal/aop/service/PersUserWidgetServiceAOP.java +++ b/portal-BE/src/main/java/org/onap/portal/aop/service/PersUserWidgetServiceAOP.java @@ -63,9 +63,10 @@ public class PersUserWidgetServiceAOP { this.dataValidator = dataValidator; } - @Before("execution(* org.onap.portal.service.PersUserWidgetService.setPersUserAppValue(..)) && args(user, personalization)") - public void setOnboardingWidget(FnUser user, WidgetCatalogPersonalization personalization) { + @Before("execution(* org.onap.portal.service.PersUserWidgetService.setPersUserAppValue(..)) && args(userId, personalization)") + public void setPersUserAppValue(final long userId, final WidgetCatalogPersonalization personalization) { if (!dataValidator.isValid(personalization)) { + LOGGER.error("IllegalArgumentException for user " + userId); throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(personalization)); } } diff --git a/portal-BE/src/main/java/org/onap/portal/aop/service/WidgetServiceAOP.java b/portal-BE/src/main/java/org/onap/portal/aop/service/WidgetServiceAOP.java index c1357e2a..6902abb3 100644 --- a/portal-BE/src/main/java/org/onap/portal/aop/service/WidgetServiceAOP.java +++ b/portal-BE/src/main/java/org/onap/portal/aop/service/WidgetServiceAOP.java @@ -2,6 +2,7 @@ package org.onap.portal.aop.service; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; +import org.onap.portal.domain.db.fn.FnWidget; import org.onap.portal.domain.dto.transport.OnboardingWidget; import org.onap.portal.validation.DataValidator; import org.slf4j.Logger; @@ -26,7 +27,16 @@ public class WidgetServiceAOP { @Before("execution(* org.onap.portal.service.widget.WidgetService.setOnboardingWidget(..)) && args(userId, onboardingWidget)") public void setOnboardingWidget(final Long userId, OnboardingWidget onboardingWidget) { if (!dataValidator.isValid(onboardingWidget)) { + LOGGER.error("IllegalArgumentException for user " + userId + "method" + "setOnboardingWidget()"); throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(onboardingWidget)); } } + + @Before("execution(* org.onap.portal.service.widget.WidgetService.saveOne(..)) && args(widget)") + public void saveOne(final FnWidget widget) { + if (!dataValidator.isValid(widget)) { + LOGGER.error("IllegalArgumentException"); + throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(widget)); + } + } } diff --git a/portal-BE/src/main/java/org/onap/portal/aop/service/ep/EpPersUserWidgetSelServiceAOP.java b/portal-BE/src/main/java/org/onap/portal/aop/service/ep/EpPersUserWidgetSelServiceAOP.java new file mode 100644 index 00000000..ae5bf8b5 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/aop/service/ep/EpPersUserWidgetSelServiceAOP.java @@ -0,0 +1,73 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.aop.service.ep; + +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.onap.portal.domain.db.ep.EpPersUserWidgetSel; +import org.onap.portal.validation.DataValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Aspect +@Component +public class EpPersUserWidgetSelServiceAOP { + + private static final Logger LOGGER = LoggerFactory.getLogger(EpPersUserWidgetSelServiceAOP.class); + + private final DataValidator dataValidator; + + @Autowired + public EpPersUserWidgetSelServiceAOP(DataValidator dataValidator) { + this.dataValidator = dataValidator; + } + + @Before("execution(* org.onap.portal.service.persUserWidgetSel.EpPersUserWidgetSelService.saveAndFlush(..)) && args(epPersUserWidgetSel)") + public void setPersUserAppValue(final EpPersUserWidgetSel epPersUserWidgetSel) { + if (!dataValidator.isValid(epPersUserWidgetSel)) { + LOGGER.error("IllegalArgumentException"); + throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(epPersUserWidgetSel)); + } + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/aop/service/FnLanguageServiceAOP.java b/portal-BE/src/main/java/org/onap/portal/aop/service/fn/FnLanguageServiceAOP.java index b62e7f7a..49db257e 100644 --- a/portal-BE/src/main/java/org/onap/portal/aop/service/FnLanguageServiceAOP.java +++ b/portal-BE/src/main/java/org/onap/portal/aop/service/fn/FnLanguageServiceAOP.java @@ -38,7 +38,7 @@ * */ -package org.onap.portal.aop.service; +package org.onap.portal.aop.service.fn; import java.security.Principal; import java.util.stream.Collectors; diff --git a/portal-BE/src/main/java/org/onap/portal/aop/service/FnUserServiceAOP.java b/portal-BE/src/main/java/org/onap/portal/aop/service/fn/FnUserServiceAOP.java index 5cbec719..274d23ad 100644 --- a/portal-BE/src/main/java/org/onap/portal/aop/service/FnUserServiceAOP.java +++ b/portal-BE/src/main/java/org/onap/portal/aop/service/fn/FnUserServiceAOP.java @@ -38,7 +38,7 @@ * */ -package org.onap.portal.aop.service; +package org.onap.portal.aop.service.fn; import java.security.Principal; import java.util.stream.Collectors; diff --git a/portal-BE/src/main/java/org/onap/portal/configuration/DBInitializingBean.java b/portal-BE/src/main/java/org/onap/portal/configuration/DBInitializingBean.java index 3f5b3883..7f928990 100644 --- a/portal-BE/src/main/java/org/onap/portal/configuration/DBInitializingBean.java +++ b/portal-BE/src/main/java/org/onap/portal/configuration/DBInitializingBean.java @@ -82,8 +82,6 @@ import org.onap.portal.service.user.FnUserService; import org.onap.portal.service.userRole.FnUserRoleService; import org.onap.portal.service.widgetCatalog.EpWidgetCatalogService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import java.math.BigInteger; @@ -1234,18 +1232,18 @@ public class DBInitializingBean implements org.springframework.beans.factory.Ini // fn_shared_context table - FnSharedContext sharedContext1 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_FIRST_NAME").cvalue("Jimmy").build(); - FnSharedContext sharedContext2 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_LAST_NAME").cvalue("Hendrix").build(); - FnSharedContext sharedContext3 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_EMAIL").cvalue("admin@onap.org").build(); - FnSharedContext sharedContext4 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_ORG_USERID").cvalue("jh0003").build(); - FnSharedContext sharedContext5 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_FIRST_NAME").cvalue("Demo").build(); - FnSharedContext sharedContext6 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_LAST_NAME").cvalue("User").build(); - FnSharedContext sharedContext7 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_EMAIL").cvalue("demo@openecomp.org").build(); - FnSharedContext sharedContext8 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_ORG_USERID").cvalue("demo").build(); - FnSharedContext sharedContext9 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_FIRST_NAME").cvalue("Demo").build(); - FnSharedContext sharedContext10 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_LAST_NAME").cvalue("User").build(); - FnSharedContext sharedContext11 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_EMAIL").cvalue("demo@openecomp.org").build(); - FnSharedContext sharedContext12 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_ORG_USERID").cvalue("demo").build(); + FnSharedContext sharedContext1 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_FIRST_NAME").cvalue("Jimmy").build(); + FnSharedContext sharedContext2 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_LAST_NAME").cvalue("Hendrix").build(); + FnSharedContext sharedContext3 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_EMAIL").cvalue("admin@onap.org").build(); + FnSharedContext sharedContext4 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_ORG_USERID").cvalue("jh0003").build(); + FnSharedContext sharedContext5 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_FIRST_NAME").cvalue("Demo").build(); + FnSharedContext sharedContext6 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_LAST_NAME").cvalue("User").build(); + FnSharedContext sharedContext7 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_EMAIL").cvalue("demo@openecomp.org").build(); + FnSharedContext sharedContext8 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_ORG_USERID").cvalue("demo").build(); + FnSharedContext sharedContext9 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_FIRST_NAME").cvalue("Demo").build(); + FnSharedContext sharedContext10 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_LAST_NAME").cvalue("User").build(); + FnSharedContext sharedContext11 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_EMAIL").cvalue("demo@openecomp.org").build(); + FnSharedContext sharedContext12 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_ORG_USERID").cvalue("demo").build(); List<FnSharedContext> sharedContexts = new ArrayList<>(Arrays.asList(sharedContext1, sharedContext2, sharedContext3, sharedContext4, sharedContext5, sharedContext6, sharedContext7, sharedContext8, sharedContext9, sharedContext10, sharedContext11, sharedContext12)); diff --git a/portal-BE/src/main/java/org/onap/portal/controller/SchedulerAuxController.java b/portal-BE/src/main/java/org/onap/portal/controller/SchedulerAuxController.java new file mode 100644 index 00000000..0df4ab91 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/SchedulerAuxController.java @@ -0,0 +1,124 @@ +/*- + * ============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============================================ + * + * + */ +package org.onap.portal.controller; + +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.json.JSONObject; +import org.onap.portal.logging.aop.EPAuditLog; +import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.scheduler.SchedulerProperties; +import org.onap.portal.scheduler.restobjects.RestObject; +import org.onap.portal.scheduler.scheduleraux.SchedulerAuxResponseWrapper; +import org.onap.portal.scheduler.scheduleraux.SchedulerAuxRestInterface; +import org.onap.portal.scheduler.scheduleraux.SchedulerAuxUtil; +import org.onap.portal.utils.PortalConstants; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(PortalConstants.PORTAL_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class SchedulerAuxController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxController.class); + + @RequestMapping(value = "/get_policy", method = RequestMethod.GET, produces = "application/json") + public ResponseEntity<String> getPolicyInfo(HttpServletRequest request) throws Exception { + try { + + logger.debug(EELFLoggerDelegate.debugLogger, + "SchedulerAux Controller Call Started: " + SchedulerProperties.SCHEDULERAUX_GET_CONFIG_VAL); + String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_GET_CONFIG_VAL); + SchedulerAuxResponseWrapper policyResWrapper = getPolicyConfig(path); + + logger.debug(EELFLoggerDelegate.debugLogger, "SchedulerAux Request END : Response: ", + new ResponseEntity<>(policyResWrapper.getResponse(), HttpStatus.OK).toString()); + + return (new ResponseEntity<>(policyResWrapper.getResponse(), + HttpStatus.valueOf(policyResWrapper.getStatus()))); + } catch (Exception e) { + SchedulerAuxResponseWrapper policyResWrapper = new SchedulerAuxResponseWrapper(); + policyResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + policyResWrapper.setEntity(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with getpolicy ", e); + return (new ResponseEntity<>(policyResWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + } + } + + private static SchedulerAuxResponseWrapper getPolicyConfig(String path) throws Exception { + String methodName = "getPolicyConfig"; + String uuid = UUID.randomUUID().toString(); + logger.debug(EELFLoggerDelegate.debugLogger, "starting getPolicyConfig "); + + try { + SchedulerAuxRestInterface policyRestController = new SchedulerAuxRestInterface(); + JSONObject request = new JSONObject(); + String policyName = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_POLICY_NAME); + request.put("policyName", policyName); + RestObject<String> restObjStr = new RestObject<>(); + String str = ""; + restObjStr.setT(str); + policyRestController.post(str, request, uuid, path, restObjStr); + SchedulerAuxResponseWrapper policyRespWrapper = SchedulerAuxUtil.wrapResponse(restObjStr); + logger.debug(EELFLoggerDelegate.debugLogger, "Getpolicy Request END : Response: ", methodName, + policyRespWrapper.getResponse()); + if (policyRespWrapper.getStatus() != 200) { + String message = String.format( + " get policy Information failed . MethodName: %s, PolicyRespWrapperResponse: %s", methodName, + policyRespWrapper.getResponse()); + logger.error(EELFLoggerDelegate.errorLogger, message); + EPLogUtil.schedulerAccessAlarm(logger, policyRespWrapper.getStatus()); + } + return policyRespWrapper; + } catch (Exception e) { + String message = String + .format(" EXCEPTION in getPolicyConfig . MethodName: %s and Exception: %s", methodName, e); + logger.error(EELFLoggerDelegate.errorLogger, "EXCEPTION in getPolicyConfig", message); + throw e; + } + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/SchedulerController.java b/portal-BE/src/main/java/org/onap/portal/controller/SchedulerController.java new file mode 100644 index 00000000..abc6a12e --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/SchedulerController.java @@ -0,0 +1,398 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.controller; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.json.JSONObject; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.PortalRestResponse; +import org.onap.portal.domain.dto.PortalRestStatusEnum; +import org.onap.portal.logging.aop.EPAuditLog; +import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.scheduler.SchedulerProperties; +import org.onap.portal.scheduler.SchedulerRestInterface; +import org.onap.portal.scheduler.SchedulerUtil; +import org.onap.portal.scheduler.restobjects.GetTimeSlotsRestObject; +import org.onap.portal.scheduler.restobjects.PostCreateNewVnfRestObject; +import org.onap.portal.scheduler.restobjects.PostSubmitVnfChangeRestObject; +import org.onap.portal.scheduler.wrapper.GetTimeSlotsWrapper; +import org.onap.portal.scheduler.wrapper.PostCreateNewVnfWrapper; +import org.onap.portal.scheduler.wrapper.PostSubmitVnfChangeTimeSlotsWrapper; +import org.onap.portal.service.AdminRolesService; +import org.onap.portal.utils.EPUserUtils; +import org.onap.portal.utils.PortalConstants; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@EPAuditLog +@RestController +@EnableAspectJAutoProxy +@RequestMapping(PortalConstants.PORTAL_AUX_API) +public class SchedulerController { + + private static final String USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL = "User is unauthorized to make this call"; + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class); + private static final DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + + private SchedulerRestInterface schedulerRestController; + private AdminRolesService adminRolesService; + + @Autowired + public SchedulerController( + final SchedulerRestInterface schedulerRestController, + final AdminRolesService adminRolesService) { + this.schedulerRestController = schedulerRestController; + this.adminRolesService = adminRolesService; + } + + @RequestMapping(value = "/get_time_slots/{scheduler_request}", method = RequestMethod.GET, produces = "application/json") + public ResponseEntity<String> getTimeSlots(HttpServletRequest request, + @PathVariable("scheduler_request") String schedulerRequest) throws Exception { + if (checkIfUserISValidToMakeSchedule(request)) { + try { + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + logger.debug(EELFLoggerDelegate.debugLogger, + "Controller Scheduler GET Timeslots for startTimeRequest: ", startTimeRequest); + logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", schedulerRequest); + + String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS) + + schedulerRequest; + + GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(path, schedulerRequest); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest = {}", + endTimeRequest); + return (new ResponseEntity<>(schedulerResWrapper.getResponse(), + HttpStatus.valueOf(schedulerResWrapper.getStatus()))); + } catch (Exception e) { + GetTimeSlotsWrapper schedulerResWrapper = new GetTimeSlotsWrapper(); + schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + schedulerResWrapper.setEntity(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e); + return (new ResponseEntity<>(schedulerResWrapper.getResponse(), + HttpStatus.INTERNAL_SERVER_ERROR)); + } + } else { + return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED)); + } + } + + @RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST, produces = "application/json") + public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request, + @RequestBody JSONObject schedulerRequest) throws Exception { + if (checkIfUserISValidToMakeSchedule(request)) { + try { + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + + logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler POST : post_create_new_vnf_change", + startTimeRequest); + + // Generating uuid + String uuid = UUID.randomUUID().toString(); + + schedulerRequest.put("scheduleId", uuid); + logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid); + + // adding uuid to the request payload + schedulerRequest.put("scheduleId", uuid); + logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", schedulerRequest.toString()); + + String path = SchedulerProperties + .getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid; + + PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(schedulerRequest, path, uuid); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST= {}", endTimeRequest); + + return new ResponseEntity<>(responseWrapper.getResponse(), + HttpStatus.valueOf(responseWrapper.getStatus())); + } catch (Exception e) { + PostCreateNewVnfWrapper responseWrapper = new PostCreateNewVnfWrapper(); + responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + responseWrapper.setEntity(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e); + return (new ResponseEntity<>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + + } + } else { + return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED)); + } + } + + @RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST, produces = "application/json") + public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request, + @RequestBody JSONObject schedulerRequest) throws Exception { + if (checkIfUserISValidToMakeSchedule(request)) { + try { + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + logger.debug(EELFLoggerDelegate.debugLogger, + " Controller Scheduler POST : submit_vnf_change_timeslots = {}", + startTimeRequest); + + // Generating uuid + String uuid = (String) schedulerRequest.get("scheduleId"); + logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid); + + schedulerRequest.remove("scheduleId"); + logger.debug(EELFLoggerDelegate.debugLogger, "Original Request for the schedulerId= {} ", + schedulerRequest.toString()); + + String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE) + .replace("{scheduleId}", uuid); + + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(schedulerRequest, + path, + uuid); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + logger.debug(EELFLoggerDelegate.debugLogger, + " Controller Scheduler - POST Submit for end time request= {}", + endTimeRequest); + + return (new ResponseEntity<>(responseWrapper.getResponse(), + HttpStatus.valueOf(responseWrapper.getStatus()))); + } catch (Exception e) { + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = new PostSubmitVnfChangeTimeSlotsWrapper(); + responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + responseWrapper.setEntity(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e); + return (new ResponseEntity<>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + + } + } else { + return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED)); + } + } + + @RequestMapping(value = "/get_scheduler_constant", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, String>> getSchedulerConstant(HttpServletRequest request, + HttpServletResponse response) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "get scheduler constant"); + + PortalRestResponse<Map<String, String>> portalRestResponse; + + if (checkIfUserISValidToMakeSchedule(request)) { + String errorMsg = " is not defined in property file. Please check the property file and make sure all the schedule constant values are defined"; + HashMap<String, String> constantMap = new HashMap<>(); + constantMap.put(SchedulerProperties.SCHEDULER_DOMAIN_NAME, "domainName"); + constantMap.put(SchedulerProperties.SCHEDULER_SCHEDULE_NAME, "scheduleName"); + constantMap.put(SchedulerProperties.SCHEDULER_WORKFLOW_NAME, "workflowName"); + constantMap.put(SchedulerProperties.SCHEDULER_CALLBACK_URL, "callbackUrl"); + constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_TYPE, "approvalType"); + constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_SUBMIT_STATUS, "approvalSubmitStatus"); + constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_REJECT_STATUS, "approvalRejectStatus"); + constantMap.put(SchedulerProperties.SCHEDULER_POLICY_NAME, "policyName"); + constantMap.put(SchedulerProperties.SCHEDULER_INTERVAL_GET_TIMESLOT_RATE, "intervalRate"); + constantMap.put(SchedulerProperties.SCHEDULER_GROUP_ID, "groupId"); + try { + Map<String, String> map = new HashMap<>(); + for (Map.Entry<String, String> entry : constantMap.entrySet()) { + if (SchedulerProperties.containsProperty(entry.getKey())) { + map.put(entry.getValue(), SchedulerProperties.getProperty(entry.getKey())); + } else { + throw new Exception(entry.getKey() + errorMsg); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}", map); + portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + map); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e); + portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + e.getMessage(), null); + } + + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "getSchedulerConstant failed: User unauthorized to make this call"); + portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "failed : Unauthorized", null); + } + return portalRestResponse; + } + + private GetTimeSlotsWrapper getTimeSlots(String path, String uuid) throws Exception { + + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Get Time Slots Request START"); + + GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<>(); + String str = ""; + + restObjStr.setT(str); + + schedulerRestController.get(str, uuid, path, restObjStr); + GetTimeSlotsWrapper schedulerRespWrapper = SchedulerUtil.getTimeSlotsWrapResponse(restObjStr); + logger.debug(EELFLoggerDelegate.debugLogger, "Get Time Slots Request END : Response: {}", + schedulerRespWrapper.getResponse()); + if (schedulerRespWrapper.getStatus() != 200 && schedulerRespWrapper.getStatus() != 204 + && schedulerRespWrapper.getStatus() != 202) { + String message = String.format( + " getTimeslots Information failed . SchedulerResponseWrapper for gettimeslots: {}", + schedulerRespWrapper.getResponse()); + logger.error(EELFLoggerDelegate.errorLogger, message); + EPLogUtil.schedulerAccessAlarm(logger, schedulerRespWrapper.getStatus()); + + } + return schedulerRespWrapper; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Get Time Slots Request ERROR : Exception:", e); + throw e; + } + } + + private PostCreateNewVnfWrapper postSchedulingRequest(JSONObject request, String path, String uuid) + throws Exception { + + try { + PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<>(); + String str = ""; + + restObjStr.setT(str); + schedulerRestController.post(str, request, path, restObjStr); + + int status = restObjStr.getStatusCode(); + if (status >= 200 && status <= 299) { + restObjStr.setUuid(uuid); + } + + PostCreateNewVnfWrapper responseWrapper = SchedulerUtil.postCreateNewVnfWrapResponse(restObjStr); + + logger.debug(EELFLoggerDelegate.debugLogger, " Post Create New Vnf Scheduling Request END : Response = {}", + responseWrapper.getResponse()); + if (responseWrapper.getStatus() != 200 && responseWrapper.getStatus() != 202 + && responseWrapper.getStatus() != 204) { + logger.error(EELFLoggerDelegate.errorLogger, "PostCreateNewVnfWrapper Information failed", + responseWrapper.getResponse()); + EPLogUtil.schedulerAccessAlarm(logger, responseWrapper.getStatus()); + + } + return responseWrapper; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "PostCreateNewVnfWrapper failed . Post Create New Vnf Scheduling Request ERROR :", e); + throw e; + } + } + + private PostSubmitVnfChangeTimeSlotsWrapper postSubmitSchedulingRequest(JSONObject request, String path, + String uuid) throws Exception { + + try { + PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<>(); + String str = ""; + + restObjStr.setT(str); + schedulerRestController.post(str, request, path, restObjStr); + + int status = restObjStr.getStatusCode(); + if (status >= 200 && status <= 299) { + status = (status == 204) ? 200 : status; + restObjStr.setStatusCode(status); + restObjStr.setUuid(uuid); + } + + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = SchedulerUtil + .postSubmitNewVnfWrapResponse(restObjStr); + logger.debug(EELFLoggerDelegate.debugLogger, "Post Submit Scheduling Request END : Response = {}", + responseWrapper.getResponse()); + if (responseWrapper.getStatus() != 200 && responseWrapper.getStatus() != 202 + && responseWrapper.getStatus() != 204) { + logger.error(EELFLoggerDelegate.errorLogger, "PostCreateNewVnfWrapper Information failed", + responseWrapper.getResponse()); + EPLogUtil.schedulerAccessAlarm(logger, responseWrapper.getStatus()); + + } + return responseWrapper; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " PostCreateNewVnfWrapper failed . Post Submit Scheduling Request ERROR :", e); + throw e; + } + } + + private String getPath(HttpServletRequest request) { + String requestURI = request.getRequestURI(); + String portalApiPath = ""; + if (requestURI != null) { + String[] uriArray = requestURI.split("/portalApi/"); + if (uriArray.length > 1) { + portalApiPath = uriArray[1]; + } + } + return portalApiPath; + } + + private boolean checkIfUserISValidToMakeSchedule(HttpServletRequest request) throws Exception { + FnUser user = EPUserUtils.getUserSession(request); + String portalApiPath = getPath(request); + Set<String> functionCodeList = adminRolesService.getAllAppsFunctionsOfUser(user.getId().toString()); + return EPUserUtils.matchRoleFunctions(portalApiPath, functionCodeList); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/SharedContextRestController.java b/portal-BE/src/main/java/org/onap/portal/controller/SharedContextRestController.java new file mode 100644 index 00000000..85425462 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/SharedContextRestController.java @@ -0,0 +1,264 @@ +/*- + * ============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============================================ + * + * + */ +package org.onap.portal.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.annotations.ApiOperation; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.portal.domain.db.fn.FnSharedContext; +import org.onap.portal.domain.dto.ecomp.SharedContext; +import org.onap.portal.exception.NotValidDataException; +import org.onap.portal.logging.aop.EPAuditLog; +import org.onap.portal.service.sharedContext.FnSharedContextService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.PortalConstants; +import org.onap.portal.validation.DataValidator; +import org.onap.portal.validation.SecureString; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + + +@Configuration +@RestController +@RequestMapping(PortalConstants.REST_AUX_API + "/context") +@EnableAspectJAutoProxy +@EPAuditLog +public class SharedContextRestController { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class); + private static final ObjectMapper mapper = new ObjectMapper(); + + private final FnSharedContextService contextService; + private final DataValidator dataValidator; + + @Autowired + public SharedContextRestController(FnSharedContextService contextService, + DataValidator dataValidator) { + this.contextService = contextService; + this.dataValidator = dataValidator; + } + + @ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class) + @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json") + public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) + throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey); + if (context_id == null || ckey == null) + throw new Exception("Received null for context_id and/or ckey"); + SecureString secureContextId = new SecureString(context_id); + SecureString secureCKey = new SecureString(ckey); + + if(!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)){ + throw new NotValidDataException("Received not valid for context_id and/or ckey"); + } + + FnSharedContext context = contextService.getFnSharedContext(context_id, ckey); + String jsonResponse; + if (context == null) + jsonResponse = convertResponseToJSON(context); + else + jsonResponse = mapper.writeValueAsString(context); + + return jsonResponse; + } + + @ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List") + @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json") + public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id); + if (context_id == null) + throw new Exception("Received null for context_id"); + SecureString secureContextId = new SecureString(context_id); + if (!dataValidator.isValid(secureContextId)) + throw new NotValidDataException("context_id is not valid"); + + List<FnSharedContext> listSharedContext = new ArrayList<>(); + FnSharedContext firstNameContext = contextService.getFnSharedContext(context_id, + EPCommonSystemProperties.USER_FIRST_NAME); + FnSharedContext lastNameContext = contextService.getFnSharedContext(context_id, + EPCommonSystemProperties.USER_LAST_NAME); + FnSharedContext emailContext = contextService.getFnSharedContext(context_id, EPCommonSystemProperties.USER_EMAIL); + FnSharedContext orgUserIdContext = contextService.getFnSharedContext(context_id, + EPCommonSystemProperties.USER_ORG_USERID); + if (firstNameContext != null) + listSharedContext.add(firstNameContext); + if (lastNameContext != null) + listSharedContext.add(lastNameContext); + if (emailContext != null) + listSharedContext.add(emailContext); + if (orgUserIdContext != null) + listSharedContext.add(orgUserIdContext); + return convertResponseToJSON(listSharedContext); + } + + @ApiOperation(value = "Tests for presence of the specified key in the specified context.") + @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json") + public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) + throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "checkContext for " + context_id + ", key " + ckey); + if (context_id == null || ckey == null) + throw new Exception("Received null for contextId and/or key"); + + SecureString secureContextId = new SecureString(context_id); + SecureString secureCKey = new SecureString(ckey); + + if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)) + throw new NotValidDataException("Not valid data for contextId and/or key"); + + String response = null; + FnSharedContext context = contextService.getFnSharedContext(context_id, ckey); + if (context != null) + response = "exists"; + + return convertResponseToJSON(response); + } + + @ApiOperation(value = "Removes the specified key in the specified context.") + @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json") + public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) + throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "removeContext for " + context_id + ", key " + ckey); + if (context_id == null || ckey == null) + throw new Exception("Received null for contextId and/or key"); + + SecureString secureContextId = new SecureString(context_id); + SecureString secureCKey = new SecureString(ckey); + + if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)) + throw new NotValidDataException("Not valid data for contextId and/or key"); + + FnSharedContext context = contextService.getFnSharedContext(context_id, ckey); + String response = null; + if (context != null) { + contextService.delete(context); + response = "removed"; + } + + return convertResponseToJSON(response); + } + + @ApiOperation(value = "Clears all key-value pairs in the specified context.") + @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json") + public String clearContext(HttpServletRequest request, @RequestParam String contextId) throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + contextId); + if (contextId == null) + throw new Exception("clearContext: Received null for contextId"); + + SecureString secureContextId = new SecureString(contextId); + + if (!dataValidator.isValid(secureContextId)) + throw new NotValidDataException("Not valid data for contextId"); + + int count = contextService.deleteSharedContexts(contextId); + return convertResponseToJSON(Integer.toString(count)); + } + + @ApiOperation(value = "Sets a context value for the specified context and key. Creates the context if no context with the specified ID-key pair exists, overwrites the value if it exists already.") + @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json") + public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception { + if (userJson !=null){ + SecureString secureUserJson = new SecureString(userJson); + if (!dataValidator.isValid(secureUserJson)) + throw new NotValidDataException("Not valid data for userJson"); + } + + @SuppressWarnings("unchecked") + Map<String, Object> userData = mapper.readValue(userJson, Map.class); + // Use column names as JSON tags + final String contextId = (String) userData.get("context_id"); + final String key = (String) userData.get("ckey"); + final String value = (String) userData.get("cvalue"); + if (contextId == null || key == null) + throw new Exception("setContext: received null for contextId and/or key"); + + logger.debug(EELFLoggerDelegate.debugLogger, "setContext: ID " + contextId + ", key " + key + "->" + value); + String response; + FnSharedContext existing = contextService.getFnSharedContext(contextId, key); + if (existing == null) { + contextService.addFnSharedContext(contextId, key, value); + } else { + existing.setCvalue(value); + contextService.save(existing); + } + response = existing == null ? "added" : "replaced"; + return convertResponseToJSON(response); + } + + private String convertResponseToJSON(String responseBody) throws JsonProcessingException { + Map<String, String> responseMap = new HashMap<>(); + responseMap.put("response", responseBody); + return mapper.writeValueAsString(responseMap); + } + + private String convertResponseToJSON(List<FnSharedContext> contextList) throws JsonProcessingException { + return mapper.writeValueAsString(contextList); + } + + private String convertResponseToJSON(FnSharedContext context) throws JsonProcessingException { + Map<String, Object> responseMap = new HashMap<>(); + responseMap.put("response", context); + return mapper.writeValueAsString(responseMap); + } + + @ExceptionHandler(Exception.class) + protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException { + logger.error(EELFLoggerDelegate.errorLogger, "handleBadRequest caught exception", e); + response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage()); + } + +} + diff --git a/portal-BE/src/main/java/org/onap/portal/controller/TicketEventController.java b/portal-BE/src/main/java/org/onap/portal/controller/TicketEventController.java new file mode 100644 index 00000000..8610af23 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/TicketEventController.java @@ -0,0 +1,238 @@ +/*- + * ============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============================================ + * + * + */ + +package org.onap.portal.controller; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.annotations.ApiOperation; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import org.onap.portal.domain.db.ep.EpNotification; +import org.onap.portal.domain.db.ep.EpRoleNotification; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.PortalRestResponse; +import org.onap.portal.domain.dto.PortalRestStatusEnum; +import org.onap.portal.logging.aop.EPAuditLog; +import org.onap.portal.service.epNotification.EpNotificationService; +import org.onap.portal.service.user.FnUserService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.PortalConstants; +import org.onap.portal.validation.DataValidator; +import org.onap.portal.validation.SecureString; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class TicketEventController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class); + + private static final String EVENT_DATE = "eventDate"; + private final ObjectMapper objectMapper = new ObjectMapper(); + + private final DataValidator dataValidator; + private final FnUserService fnUserService; + private final EpNotificationService epNotificationService; + + @Autowired + public TicketEventController(final DataValidator dataValidator, + final FnUserService fnUserService, + final EpNotificationService epNotificationService) { + this.dataValidator = dataValidator; + this.fnUserService = fnUserService; + this.epNotificationService = epNotificationService; + } + + @ApiOperation( + value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", + response = PortalRestResponse.class) + @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST) + public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response, + @RequestBody String ticketEventJson) { + + logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson); + PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + + if(!dataValidator.isValid(ticketEventJson)){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + + try { + JsonNode ticketEventNotif = objectMapper.readTree(ticketEventJson); + + // Reject request if required fields are missing. + String error = validateTicketEventMessage(ticketEventNotif); + if (error != null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(error); + response.setStatus(400); + return portalResponse; + } + + EpNotification epItem = new EpNotification(); + epItem.setCreatedDate(LocalDateTime.now()); + epItem.setIsForOnlineUsers(true); + epItem.setIsForAllRoles(false); + epItem.setActiveYn(false); + + JsonNode event = ticketEventNotif.get("event"); + JsonNode header = event.get("header"); + JsonNode body = event.get("body"); + JsonNode application = ticketEventNotif.get("application"); + epItem.setMsgDescription(body.toString()); + long eventDate = System.currentTimeMillis(); + if (body.get(EVENT_DATE) != null) { + eventDate = body.get(EVENT_DATE).asLong(); + } + String eventSource = header.get("eventSource").asText(); + epItem.setMsgSource(eventSource); + String ticket = body.get("ticketNum").asText(); + String hyperlink = this.getNotificationHyperLink(application, ticket, eventSource); + if (body.get("notificationHyperlink") != null) { + hyperlink = body.get("notificationHyperlink").asText(); + } + epItem.setNotificationHyperlink(hyperlink); + epItem.setStartTime(LocalDateTime.now()); + epItem.setEndTime(epItem.getStartTime().plusDays(30)); + String severityString = "1"; + if (body.get("severity") != null) { + severityString = (body.get("severity").toString()).substring(1, 2); + } + Long severity = Long.parseLong(severityString); + epItem.setPriority(severity); + epItem.setCreatorId(null); + JsonNode subscriberInfo = ticketEventNotif.get("SubscriberInfo"); + JsonNode userList = subscriberInfo.get("UserList"); + String[] userIds = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + .split(","); + String assetID = eventSource + ' ' + + userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + ' ' + + new Date(eventDate); + if (body.get("assetID") != null) { + assetID = body.get("assetID").asText(); + } + epItem.setMsgHeader(assetID); + List<FnUser> users = fnUserService.getUsersByOrgIds(new ArrayList<>(Arrays.asList(userIds))); + Set<EpRoleNotification> roles = new HashSet<>(); + for (String userId : userIds) { + EpRoleNotification roleNotifItem = new EpRoleNotification(); + for (FnUser user : users) { + if (user.getOrgUserId().equals(userId)) { + roleNotifItem.setRecvUserId(user.getId()); + roles.add(roleNotifItem); + break; + } + } + + } + epItem.setEpRoleNotifications(roles); + epNotificationService.saveNotification(epItem); + + portalResponse.setStatus(PortalRestStatusEnum.OK); + portalResponse.setMessage("processEventNotification: notification created"); + portalResponse.setResponse("NotificationId is :" + epItem.getNotificationId()); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Expection in handleRequest", ex); + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + response.setStatus(400); + portalResponse.setMessage(ex.toString()); + } + return portalResponse; + } + + private String getNotificationHyperLink(JsonNode application, String ticket, String eventSource) { + return (SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_SYSTEM_NOTIFICATION_URL)+ticket); + } + + private String validateTicketEventMessage(JsonNode ticketEventNotif) { + 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 || application.asText().length() == 0 || "null".equalsIgnoreCase(application.asText())) + return "Application is mandatory"; + if (body == null) + return "body is mandatory"; + if (eventSource == null || eventSource.asText().trim().length() == 0 + || "null".equalsIgnoreCase(eventSource.asText())) + return "Message Source is mandatory"; + if (userList == null) + return "At least one user Id is mandatory"; + JsonNode eventDate = body.get(EVENT_DATE); + + if (eventDate != null && eventDate.asText().length() == 8) + return "EventDate is invalid"; + String[] userIds = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + .split(","); + List<FnUser> users = fnUserService.getUsersByOrgIds(new ArrayList<>(Arrays.asList(userIds))); + fnUserService.getUsersByOrgIds(new ArrayList<>(Arrays.asList(userIds))); + if (users == null || users.isEmpty()) + return "Invalid Org User ID"; + return null; + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/TicketEventVersionController.java b/portal-BE/src/main/java/org/onap/portal/controller/TicketEventVersionController.java new file mode 100644 index 00000000..5524e6ae --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/TicketEventVersionController.java @@ -0,0 +1,61 @@ +/*- + * ============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============================================ + * + */ +package org.onap.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.portal.annotation.ApiVersion; +import org.onap.portal.domain.dto.PortalRestResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.RestController; + +@ApiVersion +@RestController +@EnableAspectJAutoProxy +public class TicketEventVersionController { + + @Autowired + TicketEventController ticketEventController; + + @ApiVersion(max = "v3", service = "/v3/ticketevent", min = 0, method = "POST") + public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response, + String ticketEventJson) throws Exception { + return ticketEventController.handleRequest(request, response, ticketEventJson); + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/UserNotificationController.java b/portal-BE/src/main/java/org/onap/portal/controller/UserNotificationController.java new file mode 100644 index 00000000..12dc922f --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/UserNotificationController.java @@ -0,0 +1,254 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.controller; + +import java.security.Principal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.portal.domain.db.ep.EpNotification; +import org.onap.portal.domain.db.ep.EpRoleNotification; +import org.onap.portal.domain.db.fn.FnMenuFunctionalRoles; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.PortalRestResponse; +import org.onap.portal.domain.dto.PortalRestStatusEnum; +import org.onap.portal.domain.dto.ecomp.EcompAppRole; +import org.onap.portal.domain.dto.transport.EpNotificationItemVO; +import org.onap.portal.logging.aop.EPAuditLog; +import org.onap.portal.service.EcompAppRoleService; +import org.onap.portal.service.EpNotificationItemVOService; +import org.onap.portal.service.epNotification.EpNotificationService; +import org.onap.portal.service.epRoleNotification.EpRoleNotificationService; +import org.onap.portal.service.epUserNotification.EpUserNotificationService; +import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService; +import org.onap.portal.service.user.FnUserService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@EnableAspectJAutoProxy +@EPAuditLog +public class UserNotificationController { + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserNotificationController.class); + + private final FnMenuFunctionalRolesService functionalMenuService; + private final FnUserService fnUserService; + private final EpNotificationService userNotificationService; + private final EpUserNotificationService epUserNotificationService; + private final EpRoleNotificationService roleNotificationService; + private final EcompAppRoleService ecompAppRoleService; + private final EpNotificationItemVOService epNotificationItemVOService; + + private static final String SUCCESS = "success"; + private static final String FAILURE = "FAILURE"; + + @Autowired + public UserNotificationController( + final FnMenuFunctionalRolesService functionalMenuService, final FnUserService fnUserService, + final EpNotificationService epNotificationService, + final EpUserNotificationService epUserNotificationService, + final EpRoleNotificationService roleNotificationService, + final EcompAppRoleService ecompAppRoleService, + final EpNotificationItemVOService epNotificationItemVOService) { + this.functionalMenuService = functionalMenuService; + this.fnUserService = fnUserService; + this.userNotificationService = epNotificationService; + this.epUserNotificationService = epUserNotificationService; + this.roleNotificationService = roleNotificationService; + this.ecompAppRoleService = ecompAppRoleService; + this.epNotificationItemVOService = epNotificationItemVOService; + } + + @RequestMapping(value = { + "/portalApi/getFunctionalMenuRole" }, method = RequestMethod.GET, produces = "application/json") + public List<FnMenuFunctionalRoles> getMenuIdRoleId(Principal principal, HttpServletRequest request, HttpServletResponse response) { + return functionalMenuService.findAll(); + } + + @RequestMapping(value = { + "/portalApi/getNotifications" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<List<EpNotification>> getNotifications(Principal principal, HttpServletRequest request, + HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + PortalRestResponse<List<EpNotification>> portalRestResponse = null; + try { + List<EpNotification> notificationList = userNotificationService.getNotifications(user.getId()); + portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS, + notificationList); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e); + portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + e.getMessage(), null); + } + return portalRestResponse; + } + + @RequestMapping(value = { + "/portalApi/getAdminNotifications" }, method = RequestMethod.GET, produces = "application/json") + public List<EpNotificationItemVO> getAdminNotifications(Principal principal, HttpServletRequest request, HttpServletResponse response) { + List<EpNotificationItemVO> adminNotificationList = null; + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + adminNotificationList = userNotificationService.getAdminNotificationVOS(user.getId()); + return adminNotificationList; + } + + @RequestMapping(value = "/portalApi/saveNotification", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> save(Principal principal, HttpServletRequest request, HttpServletResponse response, + @RequestBody EpNotification notificationItem) { + FnUser fnUser = fnUserService.loadUserByUsername(principal.getName()); + if (notificationItem == null || notificationItem.getMsgHeader() == null) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE, + "Notification Header cannot be null or empty"); + if (notificationItem.getEndTime().compareTo(notificationItem.getStartTime()) < 0) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE, + "End Time should be greater than start time"); + } + + if (("N".equals(notificationItem.getIsForAllRoles())) && notificationItem.getRoleIds().isEmpty()) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE, + "No Roles Ids Exist for the selected Roles"); + } + + Long creatorId = UserUtils.getUserIdAsLong(request); + notificationItem.setCreatorId(fnUser); + + //TODO + // Front-end date picker does not accept a time value, so all + // values are the start of the chosen day in the local time zone. + // Move the end time value to the very end of the chosen day. + // Avoid Calendar.getDefault() which uses the server's locale. + //Long endTime = notificationItem.getEndTime() + //endTime += (23 * 3600 + 59 * 60 + 59) * 1000; + //notificationItem.getEndTime().setTime(endTime); + + try { + userNotificationService.saveNotification(notificationItem); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveNotification failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE, e.getMessage()); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", ""); + } + + @RequestMapping(value = { + "/portalApi/notificationUpdateRate" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, String>> getNotificationUpdateRate(HttpServletRequest request) { + try { + String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_RATE); + String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_DURATION); + Integer rateInMiliSec = Integer.parseInt(updateRate) * 1000; + Integer durationInMiliSec = Integer.parseInt(updateDuration) * 1000; + Map<String, String> results = new HashMap<>(); + results.put("updateRate", String.valueOf(rateInMiliSec)); + results.put("updateDuration", String.valueOf(durationInMiliSec)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS, results); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getNotificationUpdateRate failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null); + } + } + + @RequestMapping(value = { + "/portalApi/notificationRead" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, String>> notificationRead( + @RequestParam("notificationId") Long notificationID, HttpServletRequest request) { + try { + epUserNotificationService.setNotificationRead(notificationID, UserUtils.getUserId(request)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "notificationRead failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null); + } + } + + @RequestMapping(value = { + "/portalApi/getNotificationHistory" }, method = RequestMethod.GET, produces = "application/json") + public List<EpNotificationItemVO> getNotificationHistory(Principal principal, HttpServletRequest request, HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + return epNotificationItemVOService.getNotificationHistoryVO(user.getId()); + } + + @RequestMapping(value = { "/portalApi/notificationRole/{notificationId}/roles" }, method = { + RequestMethod.GET }, produces = "application/json") + public List<Long> testGetRoles(HttpServletRequest request, @PathVariable("notificationId") Long notificationId) { + List<EpRoleNotification> notifRoles = roleNotificationService.getNotificationRoles(notificationId); + ArrayList<Long> rolesList = new ArrayList<>(); + for (EpRoleNotification notifRole : notifRoles) { + rolesList.add(notifRole.getRoleId().getId()); + } + return rolesList; + } + + @RequestMapping(value = { "/portalApi/getNotificationAppRoles" }, method = { + RequestMethod.GET }, produces = "application/json") + public List<EcompAppRole> getNotificationAppRoles(HttpServletRequest request, HttpServletResponse response) { + List<EcompAppRole> epAppRoleList = null; + try { + epAppRoleList = ecompAppRoleService.getAppRoleList(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while performing UserNofiticationController.getNotificationAppRoles. Details: ", + e); + } + return epAppRoleList; + } + + @RequestMapping(value = { + "/portalApi/getMessageRecipients" }, method = RequestMethod.GET, produces = "application/json") + public List<String> getMessageRecipients(@RequestParam("notificationId") Long notificationID) { + return userNotificationService.getMessageRecipients(notificationID); + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java b/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java index 1a2cb5d0..9b29f5d9 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java @@ -266,10 +266,10 @@ public class UserRolesController { FnUser user = fnUserService.loadUserByUsername(principal.getName()); List<RoleInAppForUser> result = null; String feErrorString = ""; - if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user.getId())) { + if (!adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) && !adminRolesService.isRoleAdmin(user.getId())) { logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}", - adminRolesService.isAccountAdmin(user), adminRolesService.isRoleAdmin(user.getId())); + adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()), adminRolesService.isRoleAdmin(user.getId())); EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser"); feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus()); } else { @@ -355,7 +355,7 @@ public class UserRolesController { // boolean changesApplied = false; ExternalRequestFieldsValidator changesApplied = null; - if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user.getId())) { + if (!adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) && !adminRolesService.isRoleAdmin(user.getId())) { EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser"); } else if (newAppRolesForUser == null) { logger.error(EELFLoggerDelegate.errorLogger, diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java index 20c64546..2417db37 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java @@ -68,7 +68,6 @@ import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -87,7 +86,6 @@ import org.springframework.web.client.AsyncRestTemplate; @RestController @RequestMapping(PortalConstants.REST_AUX_API) @Configuration -@EnableAspectJAutoProxy @EPAuditLog @NoArgsConstructor public class WebAnalyticsExtAppController { @@ -114,7 +112,7 @@ public class WebAnalyticsExtAppController { /** * Answers requests from partner applications for a file that is expected to * contain javascript to support web analytics. - * + * * @param request * HttpServletRequest * @return String @@ -158,7 +156,7 @@ public class WebAnalyticsExtAppController { /** * Accepts data from partner applications with web analytics data. - * + * * @param request * HttpServletRequest * @param analyticsMap @@ -209,14 +207,14 @@ public class WebAnalyticsExtAppController { } private String getAppName(HttpServletRequest request, String appName) { - + FnApp appRecord = getApp(request); if (appRecord != null) { appName = appRecord.getAppName(); } return appName; } - + private FnApp getApp(HttpServletRequest request) { String appKeyValue = request.getHeader(APP_KEY); FnApp appRecord = null; @@ -252,5 +250,5 @@ public class WebAnalyticsExtAppController { HttpMethod.POST, entity, String.class); out.addCallback(successCallback, failureCallback); } - + } diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppVersionController.java b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppVersionController.java index 87be5439..425cc55d 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppVersionController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppVersionController.java @@ -48,10 +48,8 @@ import org.onap.portal.logging.aop.EPAuditLog; import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration -@EnableAspectJAutoProxy @EPAuditLog @ApiVersion public class WebAnalyticsExtAppVersionController { diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogController.java b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogController.java index 93d6dd56..3fc5e4b8 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogController.java @@ -88,7 +88,6 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; @RestController -@EnableAspectJAutoProxy @EPAuditLog public class WidgetsCatalogController { diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogMarkupController.java b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogMarkupController.java index 4a4287c5..1c29355e 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogMarkupController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogMarkupController.java @@ -50,7 +50,6 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @@ -60,7 +59,6 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver; @EPAuditLog @RestController -@EnableAspectJAutoProxy public class WidgetsCatalogMarkupController { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogMarkupController.class); diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java index db7039fe..21494630 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java @@ -51,12 +51,11 @@ import org.onap.portal.domain.dto.transport.OnboardingWidget; import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization; import org.onap.portal.logging.aop.EPAuditLog; import org.onap.portal.service.PersUserWidgetService; -import org.onap.portal.service.widget.WidgetService; import org.onap.portal.service.user.FnUserService; +import org.onap.portal.service.widget.WidgetService; import org.onap.portal.utils.EcompPortalUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; @@ -69,7 +68,6 @@ import org.springframework.web.bind.annotation.RestController; @EPAuditLog @RestController -@EnableAspectJAutoProxy public class WidgetsController { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsController.class); @@ -96,7 +94,7 @@ public class WidgetsController { } else { String getType = request.getHeader("X-Widgets-Type"); if (!getType.isEmpty() && ("managed".equals(getType) || "all".equals(getType))) { - onboardingWidgets = widgetService.getOnboardingWidgets(user, "managed".equals(getType)); + onboardingWidgets = widgetService.getOnboardingWidgets(user.getOrgUserId(), user.getId(), "managed".equals(getType)); } else { logger.debug(EELFLoggerDelegate.debugLogger, "WidgetsController.getOnboardingApps - request must contain header 'X-Widgets-Type' with 'all' or 'managed'"); @@ -114,7 +112,7 @@ public class WidgetsController { public FieldsValidator putOnboardingWidget(Principal principal, @PathVariable("widgetId") Long widgetId, @RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) { FnUser user = fnUserService.loadUserByUsername(principal.getName()); - FieldsValidator fieldsValidator = null; + FieldsValidator fieldsValidator; assert onboardingWidget != null; onboardingWidget.setId(widgetId); @@ -167,7 +165,7 @@ public class WidgetsController { FnUser user = fnUserService.loadUserByUsername(principal.getName()); FieldsValidator fieldsValidator; - fieldsValidator = widgetService.deleteOnboardingWidget(user, widgetId); + fieldsValidator = widgetService.deleteOnboardingWidget(user.getOrgUserId(), user.getId(), widgetId); response.setStatus(fieldsValidator.getHttpStatusCode().intValue()); EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets/" + widgetId, "DELETE result =", @@ -184,7 +182,7 @@ public class WidgetsController { try { assert persRequest != null; persUserWidgetService - .setPersUserAppValue(user, persRequest); + .setPersUserAppValue(user.getId(), persRequest); } catch (IllegalArgumentException iae) { logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", iae); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, iae.getMessage()); diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpNotification.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpNotification.java index a10cc3e3..8083b24d 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpNotification.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpNotification.java @@ -42,17 +42,26 @@ package org.onap.portal.domain.db.ep; import java.io.Serializable; import java.time.LocalDateTime; +import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.ColumnResult; +import javax.persistence.ConstructorResult; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; +import javax.persistence.SqlResultSetMapping; import javax.persistence.Table; +import javax.persistence.Transient; import javax.validation.constraints.Digits; import javax.validation.constraints.FutureOrPresent; import javax.validation.constraints.NotNull; @@ -64,6 +73,8 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.validator.constraints.SafeHtml; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.transport.EpNotificationItemVO; /* CREATE TABLE `ep_notification` ( @@ -84,6 +95,77 @@ CREATE TABLE `ep_notification` ( ) */ +@NamedNativeQueries({ + @NamedNativeQuery( + name = "EpNotification.getNotifications", + query = "select rowId, notification_ID, is_for_online_users,is_for_all_roles, msg_header, msg_description,msg_source, start_Time, end_time, priority, created_date, creator_ID,notification_hyperlink, active_YN from\n" + + "( \n" + + "select notification_ID, is_for_online_users, is_for_all_roles, msg_header, msg_description, msg_source,start_Time, end_time, priority,created_date, creator_ID,notification_hyperlink,active_YN\n" + + "from\n" + + " (\n" + + " select user_id, notification_id, is_for_online_users, is_for_all_roles, msg_header, msg_description,msg_source,start_Time, end_time, priority, created_date,notification_hyperlink, creator_ID,active_YN\n" + + " from\n" + + " (\n" + + " select a.notification_ID,a.is_for_online_users,a.is_for_all_roles,a.active_YN,\n" + + " a.msg_header,a.msg_description,a.msg_source,a.start_time,a.end_time,a.priority,a.creator_ID,a.notification_hyperlink,a.created_date,b.role_id,b.recv_user_id \n" + + " from ep_notification a, ep_role_notification b\n" + + " where a.notification_id = b.notification_id\n" + + " and (end_time is null || SYSDATE() <= end_time )\n" + + " and (start_time is null || SYSDATE() >= start_time)\n" + + " and a.is_for_all_roles = 'N'\n" + + " ) a,\n" + + " (\n" + + " select distinct a.user_id, c.role_id, c.app_id, d.APP_NAME\n" + + " from fn_user a, fn_user_role b, fn_role c, fn_app d\n" + + " where COALESCE(c.app_id,1) = d.app_id\n" + + " and a.user_id = b.user_id\n" + + " and a.user_id = :user_id\n" + + " and b.role_id = c.role_id\n" + + " and (d.enabled='Y' or d.app_id=1)\n" + + " )b\n" + + " where\n" + + " (\n" + + " a.role_id = b.role_id\n" + + " )\n" + + " union\n" + + " select :user_id, notification_id, is_for_online_users, is_for_all_roles, msg_header, msg_description,msg_source,start_Time, end_time, priority, created_date,notification_hyperlink, creator_ID,active_YN\n" + + " from\n" + + " (\n" + + " select a.notification_ID,a.is_for_online_users,a.is_for_all_roles,a.active_YN,\n" + + " a.msg_header,a.msg_description,a.msg_source,a.start_time,a.end_time,a.priority,a.creator_ID,a.created_date, a.notification_hyperlink,b.role_id,b.recv_user_id \n" + + " from ep_notification a, ep_role_notification b\n" + + " where a.notification_id = b.notification_id\n" + + " and (end_time is null || SYSDATE() <= end_time )\n" + + " and (start_time is null || SYSDATE() >= start_time)\n" + + " and a.is_for_all_roles = 'N'\n" + + " ) a\n" + + " where\n" + + " (\n" + + " a.recv_user_id=:user_id\n" + + " )\n" + + " union\n" + + " (\n" + + " select :user_id user_id, notification_id, is_for_online_users, is_for_all_roles, msg_header, msg_description, msg_source,start_Time, end_time, priority, created_date,notification_hyperlink, creator_ID,active_YN\n" + + " from ep_notification a\n" + + " where a.notification_id\n" + + " and (end_time is null || SYSDATE() <= end_time )\n" + + " and (start_time is null || SYSDATE() >= start_time)\n" + + " and a.is_for_all_roles = 'Y'\n" + + " )\n" + + " ) a\n" + + " where\n" + + " active_YN = 'Y'\n" + + " and\n" + + " not exists\n" + + " (\n" + + " select ID,User_ID,notification_ID,is_viewed,updated_time from ep_user_notification m where user_id = :user_id and m.notification_id = a.notification_id and is_viewed = 'Y'\n" + + " )\n" + + " order by priority desc, created_date desc,start_Time desc\n" + + "\n" + + "\n" + + " ) t,\n")} +) + @Table(name = "ep_notification") @NoArgsConstructor @AllArgsConstructor @@ -92,26 +174,16 @@ CREATE TABLE `ep_notification` ( @Entity public class EpNotification implements Serializable { @Id - - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "notification_ID", length = 11, nullable = false) @Digits(integer = 11, fraction = 0) - private Long notificationID; - @Column(name = "is_for_online_users", length = 1, columnDefinition = "char(1) default 'N'") - @Pattern(regexp = "[YNyn]") - @Size(max = 1) - @SafeHtml - private String isForOnlineUsers; - @Column(name = "is_for_all_roles", length = 1, columnDefinition = "char(1) default 'N'") - @Pattern(regexp = "[YNyn]") - @Size(max = 1) - @SafeHtml - private String isForAllRoles; - @Column(name = "active_yn", length = 1, columnDefinition = "char(1) default 'Y'") - @Pattern(regexp = "[YNyn]") - @Size(max = 1) - @SafeHtml - private String activeYn; + private Long notificationId; + @Column(name = "is_for_online_users") + private Boolean isForOnlineUsers = false; + @Column(name = "is_for_all_roles") + private Boolean isForAllRoles = false; + @Column(name = "active_yn") + private Boolean activeYn = true; @Column(name = "msg_header", length = 100) @Size(max = 100) @SafeHtml @@ -130,13 +202,13 @@ public class EpNotification implements Serializable { private LocalDateTime startTime; @Column(name = "end_time") @FutureOrPresent - private LocalDateTime end_time; + private LocalDateTime endTime; @Column(name = "priority", length = 11) @Digits(integer = 11, fraction = 0) private Long priority; - @Column(name = "creator_ID", length = 11) + @Column(name = "creator_Id", length = 11) @Digits(integer = 11, fraction = 0) - private Long creatorID; + private FnUser creatorId; @Column(name = "created_date") @FutureOrPresent private LocalDateTime createdDate; @@ -144,9 +216,11 @@ public class EpNotification implements Serializable { @Size(max = 512) @SafeHtml private String notificationHyperlink; + @Transient + private List<Long> roleIds; @OneToMany( targetEntity = EpRoleNotification.class, - mappedBy = "notificationID", + mappedBy = "notificationId", cascade = CascadeType.MERGE, fetch = FetchType.LAZY ) diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java index 2d4c76f3..71d8da04 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java @@ -97,13 +97,13 @@ public class EpPersUserWidgetSel extends DomainVo implements Serializable { private FnUser userId; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinColumn(name = "widget_id", nullable = false) - @NotNull + @NotNull(message = "widgetId may not be null") @Valid private EpWidgetCatalog widgetId; @Column(name = "status_cd", length = 1, nullable = false) @Size(max = 1) - @NotNull - @SafeHtml + @NotNull(message = "status may not be null") + @SafeHtml(message = "status must be safeHtml") private String statusCd; } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpRoleNotification.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpRoleNotification.java index 53e48073..95ffbf2c 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpRoleNotification.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpRoleNotification.java @@ -51,6 +51,8 @@ import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.validation.Valid; @@ -76,6 +78,16 @@ CREATE TABLE `ep_role_notification` ( ) */ +@NamedQueries({ + @NamedQuery( + name = "EpRoleNotification.getNotificationRoles", + query = "from\n" + + " EpRoleNotification r\n" + + " where\n" + + " r.notificationId.notificationId = :notificationID\n" + ) +}) + @Table(name = "ep_role_notification", indexes = { @Index(name = "ep_notif_recv_user_id_idx", columnList = "recv_user_id"), @Index(name = "fk_ep_role_notif_fn_notif", columnList = "notification_ID"), @@ -88,19 +100,18 @@ CREATE TABLE `ep_role_notification` ( @Entity public class EpRoleNotification implements Serializable { @Id - - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID", length = 11, nullable = false, columnDefinition = "int(11) AUTO_INCREMENT") @Digits(integer = 11, fraction = 0) private Long id; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinColumn(name = "notification_ID") @Valid - private EpNotification notificationID; + private EpNotification notificationId; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinColumn(name = "role_ID", columnDefinition = "bigint") @Valid - private FnRole roleID; + private FnRole roleId; @Column(name = "recv_user_id", length = 11, columnDefinition = "int(11) DEFAULT NULL") @Digits(integer = 11, fraction = 0) private Long recvUserId; diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserNotification.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserNotification.java index 441eb524..ad3e2fd8 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserNotification.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserNotification.java @@ -92,11 +92,10 @@ CREATE TABLE `ep_user_notification` ( @Entity public class EpUserNotification implements Serializable { @Id - - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID", length = 11, nullable = false, columnDefinition = "int(11) AUTO_INCREMENT") @Digits(integer = 11, fraction = 0) - private Integer id; + private Long id; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinColumn(name = "User_ID", columnDefinition = "bigint") @Valid @@ -105,11 +104,8 @@ public class EpUserNotification implements Serializable { @JoinColumn(name = "notification_ID") @Valid private EpNotification notificationId; - @Column(name = "is_viewed", length = 1, columnDefinition = "char(1) default 'N'") - @Pattern(regexp = "[YNyn]") - @Size(max = 1) - @SafeHtml - private String isViewed; + @Column(name = "is_viewed", length = 1) + private Boolean isViewed = false; @Column(name = "updated_time", nullable = false, columnDefinition = "datetime default now()") @NotNull private LocalDateTime updatedTime; diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java index 0aee6155..cd906cf1 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java @@ -93,7 +93,7 @@ public class EpWidgetCatalog implements Serializable { @Size(max = 100) @NotNull @SafeHtml - private String wdgName; + private String wdgName = "?"; @Column(name = "service_id", length = 11) @Digits(integer = 11, fraction = 0) private Long serviceId; @@ -105,10 +105,10 @@ public class EpWidgetCatalog implements Serializable { @Size(max = 256) @NotNull @SafeHtml - private String wdgFileLoc; + private String wdgFileLoc = "?"; @Column(name = "all_user_flag", length = 1, columnDefinition = "boolean default false", nullable = false) @NotNull - private Boolean allUserFlag; + private Boolean allUserFlag = false; @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY) @JoinTable( name = "ep_widget_microservice", diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java index 2c16d00a..6bb13d70 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java @@ -162,7 +162,7 @@ public class FnRole extends Role { private Set<FnRoleFunction> roleFunctions; @OneToMany( targetEntity = EpRoleNotification.class, - mappedBy = "notificationID", + mappedBy = "notificationId", cascade = CascadeType.MERGE, fetch = FetchType.LAZY ) diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnSharedContext.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnSharedContext.java index ca16d343..a348ef43 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnSharedContext.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnSharedContext.java @@ -42,17 +42,17 @@ package org.onap.portal.domain.db.fn; import java.io.Serializable; import java.time.LocalDateTime; +import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.SequenceGenerator; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; -import javax.validation.constraints.PastOrPresent; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; @@ -60,6 +60,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.validator.constraints.SafeHtml; +import org.onap.portal.domain.db.DomainVo; /* CREATE TABLE `fn_shared_context` ( @@ -73,25 +74,32 @@ CREATE TABLE `fn_shared_context` ( ) */ +@NamedQueries({ + @NamedQuery( + name = "FnSharedContext.getByContextId", + query = "FROM FnSharedContext WHERE contextId = :contextId"), + @NamedQuery( + name = "FnSharedContext.getByContextIdAndCkey", + query = "FROM FnSharedContext WHERE contextId = :contextId and ckey = :ckey") +}) + +@NamedNativeQueries({ + @NamedNativeQuery( + name = "FnSharedContext.deleteByCreated", + query = "delete FnSharedContext where created < :created" + ) +}) + @Table(name = "fn_shared_context", uniqueConstraints ={ @UniqueConstraint(columnNames = {"context_Id", "ckey"}) }) @NoArgsConstructor @AllArgsConstructor -@Builder @Getter @Setter @Entity -public class FnSharedContext implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", nullable = false, length = 11, columnDefinition = "int(11) AUTO_INCREMENT") - @Digits(integer = 11, fraction = 0) - private Long id; - @Column(name = "create_time", nullable = false, columnDefinition = "timestamp DEFAULT current_timestamp() ON UPDATE current_timestamp()") - @PastOrPresent - @NotNull - private LocalDateTime createTime; +public class FnSharedContext extends DomainVo implements Serializable { + @Column(name = "context_id", length = 64, nullable = false) @Size(max = 64) @SafeHtml @@ -107,4 +115,19 @@ public class FnSharedContext implements Serializable { @SafeHtml @NotNull private String cvalue; + + @Builder + public FnSharedContext(@Digits(integer = 11, fraction = 0) Long id, + LocalDateTime created, LocalDateTime modified, Long rowNum, Serializable auditUserId, + DomainVo createdId, DomainVo modifiedId, Set<DomainVo> fnUsersCreatedId, + Set<DomainVo> fnUsersModifiedId, + @Size(max = 64) @NotNull String contextId, + @Size(max = 128) @NotNull String ckey, + @Size(max = 1024) @NotNull String cvalue) { + super(id, created, modified, rowNum, auditUserId, createdId, modifiedId, fnUsersCreatedId, + fnUsersModifiedId); + this.contextId = contextId; + this.ckey = ckey; + this.cvalue = cvalue; + } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java index 277b04d8..6800b0c5 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java @@ -523,7 +523,6 @@ public class FnUser extends DomainVo implements UserDetails, Serializable { } @Builder - public FnUser(@Digits(integer = 11, fraction = 0) Long id, LocalDateTime created, LocalDateTime modified, Long rowNum, Serializable auditUserId, DomainVo createdId, DomainVo modifiedId, Set<DomainVo> fnUsersCreatedId, Set<DomainVo> fnUsersModifiedId, FnOrg orgId, diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java index d9053f03..3625fed1 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java @@ -45,16 +45,18 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.ToString; @Getter @Setter +@ToString @NoArgsConstructor @AllArgsConstructor public class WidgetCatalogPersonalization { - @NotNull + @NotNull(message = "widgetId may not be null") private Long widgetId; - @NotNull + @NotNull(message = "select may not be null") private Boolean select; } diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerProperties.java b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerProperties.java new file mode 100644 index 00000000..74669abb --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerProperties.java @@ -0,0 +1,147 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler; + +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; + +@Configuration +@PropertySource(value = { "classpath:/conf/scheduler.properties" }) +public class SchedulerProperties { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerProperties.class); + + private static Environment environment; + + + public SchedulerProperties() { + } + + protected Environment getEnvironment() { + return environment; + } + + @Autowired + public void setEnvironment(Environment environment) { + SchedulerProperties.environment = environment; + } + + public static boolean containsProperty(String key) { + return environment.containsProperty(key); + } + + public static String getProperty(String key) { + String value = ""; + if (environment == null) { + logger.error(EELFLoggerDelegate.errorLogger, "getProperty: environment is null, should never happen!"); + } else { + value = environment.getRequiredProperty(key); + if (value != null) + value = value.trim(); + } + return value; + } + + public static final String SCHEDULER_USER_NAME_VAL = "scheduler.user.name"; + + public static final String SCHEDULER_PASSWORD_VAL = "scheduler.password"; + + public static final String SCHEDULER_SERVER_URL_VAL = "scheduler.server.url"; + + public static final String SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL = "scheduler.create.new.vnf.change.instance"; + + public static final String SCHEDULER_GET_TIME_SLOTS = "scheduler.get.time.slots"; + + public static final String SCHEDULER_SUBMIT_NEW_VNF_CHANGE = "scheduler.submit.new.vnf.change"; + + public static final String SCHEDULERAUX_CLIENTAUTH_VAL = "scheduleraux.ClientAuth"; + + public static final String SCHEDULERAUX_CLIENT_MECHID_VAL = "scheduleraux.client.mechId"; + + public static final String SCHEDULERAUX_CLIENT_PASSWORD_VAL = "scheduleraux.client.password"; + + public static final String SCHEDULERAUX_USERNAME_VAL = "scheduleraux.username"; + + public static final String SCHEDULERAUX_PASSWORD_VAL = "scheduleraux.password"; + + public static final String SCHEDULERAUX_AUTHORIZATION_VAL = "scheduleraux.Authorization"; + + public static final String SCHEDULERAUX_SERVER_URL_VAL = "scheduleraux.server.url"; + + public static final String SCHEDULERAUX_ENVIRONMENT_VAL = "scheduleraux.environment"; + + public static final String SCHEDULERAUX_GET_CONFIG_VAL = "scheduleraux.get.config"; + + + /** The Constant VID_TRUSTSTORE_FILENAME. */ + public static final String VID_TRUSTSTORE_FILENAME = "vid.truststore.filename"; + + /** The Constant VID_TRUSTSTORE_PASSWD_X. */ + public static final String VID_TRUSTSTORE_PASSWD_X = "vid.truststore.passwd.x"; + + /** The Constant FILESEPARATOR. */ + public static final String FILESEPARATOR = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator"); + + /** Scheduler UI constant **/ + public static final String SCHEDULER_DOMAIN_NAME = "scheduler.domain.name"; + + public static final String SCHEDULER_SCHEDULE_NAME = "scheduler.schedule.name"; + + public static final String SCHEDULER_WORKFLOW_NAME = "scheduler.workflow.name"; + + public static final String SCHEDULER_CALLBACK_URL = "scheduler.callback.url"; + + public static final String SCHEDULER_APPROVAL_TYPE = "scheduler.approval.type"; + + public static final String SCHEDULER_APPROVAL_SUBMIT_STATUS = "scheduler.approval.submit.status"; + + public static final String SCHEDULER_APPROVAL_REJECT_STATUS = "scheduler.approval.reject.status"; + + public static final String SCHEDULER_INTERVAL_GET_TIMESLOT_RATE = "scheduler.interval.get.timeslot.rate"; + + public static final String SCHEDULER_POLICY_NAME = "scheduler.policy.name"; + + public static final String SCHEDULER_GROUP_ID = "scheduler.group.id"; + +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerResponseWrapper.java b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerResponseWrapper.java new file mode 100644 index 00000000..4e9c6995 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerResponseWrapper.java @@ -0,0 +1,119 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Scheduler response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "status", + "entity", + "uuid" +}) + +public class SchedulerResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () throws JsonProcessingException,IOException { + Map<String, Object> map = new LinkedHashMap<>(); + map.put("status", getStatus()); + map.put("entity", getEntity()); + map.put("uuid", getUuid()); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonResponse = objectMapper.writeValueAsString(map); + return jsonResponse; + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerRestInt.java b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerRestInt.java new file mode 100644 index 00000000..7f914038 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerRestInt.java @@ -0,0 +1,54 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler; + +import org.onap.portal.utils.DateUtil; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class SchedulerRestInt { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); + + public SchedulerRestInt() { + DateUtil.getRequestDateFormat().setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerRestInterface.java b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerRestInterface.java new file mode 100644 index 00000000..a6066fdb --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerRestInterface.java @@ -0,0 +1,301 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializer; +import java.util.Collections; +import java.util.Date; +import javax.security.auth.login.CredentialException; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; +import lombok.NoArgsConstructor; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang.StringUtils; +import org.eclipse.jetty.util.security.Password; +import org.json.JSONObject; +import org.onap.portal.logging.format.EPAppMessagesEnum; +import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.scheduler.client.HttpBasicClient; +import org.onap.portal.scheduler.client.HttpsBasicClient; +import org.onap.portal.scheduler.restobjects.GetTimeSlotsRestObject; +import org.onap.portal.scheduler.restobjects.RestObject; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +@SuppressWarnings("MalformedFormatString") +@Service +@NoArgsConstructor +public class SchedulerRestInterface { + + private static final String APPLICATION_JSON = "application/json"; + private static final String PASSWORD_IS_EMPTY = "Password is Empty"; + private static final String HTTP_CLIENT_ERROR = " HttpClientErrorException: Exception For the POST ." + + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON"; + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); + private static Client client = null; + private static Gson gson = null; + + private MultivaluedHashMap<String, Object> commonHeaders; + + private static void init() { + logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); + GsonBuilder builder = new GsonBuilder(); + + // Register an adapter to manage the date types as long values + builder.registerTypeAdapter(Date.class, + (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())); + + gson = builder.create(); + } + + public void initRestClient() { + logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client"); + + init(); + + final String username; + final String password; + + /* Setting user name based on properties */ + String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL); + if (retrievedUsername.isEmpty()) { + username = ""; + } else { + username = retrievedUsername; + } + + /* Setting password based on properties */ + String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL); + if (retrievedPassword.isEmpty()) { + password = StringUtils.EMPTY; + } else { + if (retrievedPassword.contains("OBF:")) { + password = Password.deobfuscate(retrievedPassword); + } else { + password = retrievedPassword; + } + } + try { + if (StringUtils.isBlank(password)) { + throw new CredentialException(PASSWORD_IS_EMPTY); + } + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex); + } + String authString = username + ":" + password; + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + + commonHeaders = new MultivaluedHashMap<>(); + commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc))); + + try { + if (!username.isEmpty()) { + + client = HttpBasicClient.getClient(); + } else { + + client = HttpsBasicClient.getClient(); + } + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client", e.getMessage()); + + } + logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized"); + + } + + public <T> void get(String t, String sourceId, String path, GetTimeSlotsRestObject<String> restObject) { + + String methodName = "Get"; + String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + + logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url); + try { + initRestClient(); + + final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get(); + + int status = cres.getStatus(); + restObject.setStatusCode(status); + + if (cres.getEntity() != null) { + try { + String str = (cres).readEntity(String.class); + if (t.getClass().getName().equals(String.class.getName())) { + t = str; + } else { + t = gson.fromJson(str, t.getClass()); + } + + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + } else { + t = null; + restObject.setT(null); + } + + if ("".equals(t)) { + restObject.setT(null); + } else { + restObject.setT(t); + } + } catch (HttpClientErrorException e) { + String message = String.format( + HTTP_CLIENT_ERROR, methodName, url); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); + } catch (Exception e) { + String message = String + .format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, + url); + + logger.error(EELFLoggerDelegate.errorLogger, message, e); + EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); + + throw e; + + } + + } + + public <T> void post(String t, JSONObject requestDetails, String path, RestObject<String> restObject) { + + String methodName = "Post"; + String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url); + + try { + + initRestClient(); + + // Change the content length + final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders) + .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); + + if (cres != null && cres.getEntity() != null) { + + try { + String str = (cres).readEntity(String.class); + if (t.getClass().getName().equals(String.class.getName())) { + t = str; + + } else { + t = gson.fromJson(str, t.getClass()); + } + + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + restObject.setT(t); + } else { + restObject.setT(null); + } + + int status = cres != null ? cres.getStatus() : 0; + restObject.setStatusCode(status); + + if (status >= 200 && status <= 299) { + String message = String.format(" REST api POST was successful!", methodName); + logger.debug(EELFLoggerDelegate.debugLogger, message); + + } else { + String message = String.format( + " FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON", + methodName, status, url); + logger.debug(EELFLoggerDelegate.debugLogger, message); + } + + } catch (HttpClientErrorException e) { + String message = String.format( + HTTP_CLIENT_ERROR, methodName, url); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); + } catch (Exception e) { + String message = String.format( + HTTP_CLIENT_ERROR, methodName, url); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); + throw e; + } + } + + public <T> void delete(String t, JSONObject requestDetails, String sourceID, String path, RestObject<String> restObject) { + + String methodName = "Delete"; + String url = ""; + Response cres; + + try { + initRestClient(); + + url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + + cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders) + .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke(); + + int status = cres.getStatus(); + restObject.setStatusCode(status); + if (cres.getEntity() != null) { + t = cres.readEntity(t.getClass()); + restObject.setT(t); + } + + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete", + methodName, url, e); + EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception For the Delete", methodName, url, e); + EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); + throw e; + } + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerUtil.java b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerUtil.java new file mode 100644 index 00000000..ba55f477 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/SchedulerUtil.java @@ -0,0 +1,136 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Date; +import org.onap.portal.scheduler.restobjects.GetTimeSlotsRestObject; +import org.onap.portal.scheduler.restobjects.PostCreateNewVnfRestObject; +import org.onap.portal.scheduler.restobjects.PostSubmitVnfChangeRestObject; +import org.onap.portal.scheduler.wrapper.GetTimeSlotsWrapper; +import org.onap.portal.scheduler.wrapper.PostCreateNewVnfWrapper; +import org.onap.portal.scheduler.wrapper.PostSubmitVnfChangeTimeSlotsWrapper; +import org.onap.portal.utils.DateUtil; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class SchedulerUtil { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerUtil.class); + + public static GetTimeSlotsWrapper getTimeSlotsWrapResponse(GetTimeSlotsRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + + if (rs != null) { + resp_str = rs.getT(); + status = rs.getStatusCode(); + } + + GetTimeSlotsWrapper w = new GetTimeSlotsWrapper(); + + w.setEntity(resp_str); + w.setStatus(status); + + return (w); + } + + public static PostSubmitVnfChangeTimeSlotsWrapper postSubmitNewVnfWrapResponse( + PostSubmitVnfChangeRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + String uuid = ""; + + if (rs != null) { + resp_str = rs.getT(); + status = rs.getStatusCode(); + uuid = rs.getUuid(); + } + + PostSubmitVnfChangeTimeSlotsWrapper w = new PostSubmitVnfChangeTimeSlotsWrapper(); + + w.setEntity(resp_str); + w.setStatus(status); + w.setUuid(uuid); + + return (w); + } + + public static PostCreateNewVnfWrapper postCreateNewVnfWrapResponse(PostCreateNewVnfRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + String uuid = ""; + + if (rs != null) { + resp_str = rs.getT(); + status = rs.getStatusCode(); + uuid = rs.getUUID(); + } + + PostCreateNewVnfWrapper w = new PostCreateNewVnfWrapper(); + + w.setEntity(resp_str); + w.setStatus(status); + w.setUuid(uuid); + + return (w); + } + + public static <T> String convertPojoToString(T t) throws com.fasterxml.jackson.core.JsonProcessingException { + + String methodName = "convertPojoToString"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if (t != null) { + try { + r_json_str = mapper.writeValueAsString(t); + } catch (com.fasterxml.jackson.core.JsonProcessingException j) { + logger.debug(EELFLoggerDelegate.debugLogger, + DateUtil.getDateFormat().format(new Date()) + "<== " + methodName + " Unable " + "to " + + "parse object as json"); + } + } + return (r_json_str); + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/client/HttpBasicClient.java b/portal-BE/src/main/java/org/onap/portal/scheduler/client/HttpBasicClient.java new file mode 100644 index 00000000..c09aa12b --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/client/HttpBasicClient.java @@ -0,0 +1,73 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ +package org.onap.portal.scheduler.client; + + +import javax.servlet.ServletContext; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.onap.portal.scheduler.util.CustomJacksonJaxBJsonProvider; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; + +public class HttpBasicClient{ + + @Autowired + private ServletContext servletContext; + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpBasicClient.class); + /** + * Obtain a basic HTTP client . + * + * @return Client client object + * @throws Exception the exception + */ + public static Client getClient() throws Exception { + + ClientConfig config = new ClientConfig(); + config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + + return ClientBuilder.newClient(config) + .register(CustomJacksonJaxBJsonProvider.class); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/client/HttpsBasicClient.java b/portal-BE/src/main/java/org/onap/portal/scheduler/client/HttpsBasicClient.java new file mode 100644 index 00000000..1f44525b --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/client/HttpsBasicClient.java @@ -0,0 +1,113 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.client; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.onap.portal.scheduler.SchedulerProperties; +import org.eclipse.jetty.util.security.Password; +import org.onap.portal.scheduler.util.CustomJacksonJaxBJsonProvider; +import org.onap.portal.utils.DateUtil; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class HttpsBasicClient { + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsBasicClient.class); + + public static Client getClient() throws Exception { + String methodName = "getClient"; + ClientConfig config = new ClientConfig(); + + SSLContext ctx = null; + + try { + + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); + config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + + String truststore_path = SchedulerProperties.getProperty(SchedulerProperties.VID_TRUSTSTORE_FILENAME); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " " + + "truststore_path=" + + truststore_path); + String truststore_password = SchedulerProperties.getProperty(SchedulerProperties.VID_TRUSTSTORE_PASSWD_X); + + String decrypted_truststore_password = Password.deobfuscate(truststore_password); + + File tr = new File(truststore_path); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " absolute " + + "truststore path=" + tr.getAbsolutePath()); + System.setProperty("javax.net.ssl.trustStore", truststore_path); + System.setProperty("javax.net.ssl.trustStorePassword", decrypted_truststore_password); + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + public boolean verify(String string, SSLSession ssls) { + return true; + } + }); + ctx = SSLContext.getInstance("TLSv1.2"); + ctx.init(null, null, null); + + return ClientBuilder.newBuilder() + .sslContext(ctx) + .hostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String s, SSLSession sslSession) { + return true; + } + }).withConfig(config) + .build() + .register(CustomJacksonJaxBJsonProvider.class); + + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config: exiting"); + e.printStackTrace(); + return null; + } + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/policy/rest/RequestDetails.java b/portal-BE/src/main/java/org/onap/portal/scheduler/policy/rest/RequestDetails.java new file mode 100644 index 00000000..5dc1b8cf --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/policy/rest/RequestDetails.java @@ -0,0 +1,127 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.policy.rest; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +/* + [ + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_zone_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf_zone\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + }, + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_pserver_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf_pserver\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_pserver_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + }, + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_vnf_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_vnf_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + } + ] +*/ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "policyConfigMessage", + "policyConfigStatus", + "type", + "config", + "policyName", + "policyVersion", + "matchingConditions" +}) +public class RequestDetails { + + @JsonProperty("policyName") + private String policyName; + + @JsonProperty("policyName") + public String getPolicyName() { + return policyName; + } + + @JsonProperty("policyName") + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/GetTimeSlotsRestObject.java b/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/GetTimeSlotsRestObject.java new file mode 100644 index 00000000..9b58266b --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/GetTimeSlotsRestObject.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.restobjects; + +public class GetTimeSlotsRestObject<T> extends RestObject<T> { +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/PostCreateNewVnfRestObject.java b/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/PostCreateNewVnfRestObject.java new file mode 100644 index 00000000..c6aadd58 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/PostCreateNewVnfRestObject.java @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.restobjects; + +public class PostCreateNewVnfRestObject<T> extends RestObject<T> { + + private String uuid; + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/PostSubmitVnfChangeRestObject.java b/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/PostSubmitVnfChangeRestObject.java new file mode 100644 index 00000000..5e180865 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/PostSubmitVnfChangeRestObject.java @@ -0,0 +1,45 @@ + +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.restobjects; + +public class PostSubmitVnfChangeRestObject<T> extends RestObject<T> { +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/RestObject.java b/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/RestObject.java new file mode 100644 index 00000000..f0a67ae8 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/restobjects/RestObject.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.restobjects; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class RestObject<T> { + + private T t; + private int statusCode= 0; + private String uuid; + + public T getT() { + return t; + } + public void setT(T t) { + this.t = t; + } +} + diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxResponseWrapper.java b/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxResponseWrapper.java new file mode 100644 index 00000000..cb1fa59b --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxResponseWrapper.java @@ -0,0 +1,96 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.scheduleraux; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Policy response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "status", + "entity" +}) + +public class SchedulerAuxResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": " ).append(this.getEntity()).append("}"); + return (b.toString()); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxRestInt.java b/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxRestInt.java new file mode 100644 index 00000000..978d68fe --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxRestInt.java @@ -0,0 +1,84 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.scheduleraux; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.text.SimpleDateFormat; +import java.util.Date; +import org.onap.portal.scheduler.policy.rest.RequestDetails; +import org.onap.portal.utils.DateUtil; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class SchedulerAuxRestInt { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class); + + public SchedulerAuxRestInt() { + DateUtil.getRequestDateFormat().setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + } + + /** + * Log request. + * + * @param r the r + */ + public void logRequest ( RequestDetails r ) { + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); + String methodName = "logRequest"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( r != null ) { + r_json_str = r.toString(); + try { + r_json_str = mapper.writeValueAsString(r); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " " + + "Unable to " + + "parse request as json"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=" + + "(" + + r_json_str + ")"); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxRestInterface.java b/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxRestInterface.java new file mode 100644 index 00000000..fbd96079 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxRestInterface.java @@ -0,0 +1,319 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.scheduleraux; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import java.lang.reflect.Type; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; +import org.apache.commons.codec.binary.Base64; +import org.apache.cxf.jaxrs.impl.ResponseImpl; +import org.eclipse.jetty.util.security.Password; +import org.json.JSONObject; +import org.onap.portal.logging.format.EPAppMessagesEnum; +import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.scheduler.SchedulerProperties; +import org.onap.portal.scheduler.client.HttpBasicClient; +import org.onap.portal.scheduler.policy.rest.RequestDetails; +import org.onap.portal.scheduler.restobjects.RestObject; +import org.onap.portal.utils.DateUtil; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + +public class SchedulerAuxRestInterface { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class); + + /** The client. */ + private static Client client = null; + + /** The common headers. */ + private MultivaluedHashMap<String, Object> commonHeaders; + + public SchedulerAuxRestInterface() { + super(); + } + + Gson gson = null; + + private final ObjectMapper mapper = new ObjectMapper(); + + private void init() { + logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); + GsonBuilder builder = new GsonBuilder(); + + // Register an adapter to manage the date types as long values + builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); + + gson = builder.create(); + } + + public void initRestClient() { + init(); + final String methodname = "initRestClient()"; + final String mechId = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_MECHID_VAL); + final String clientPassword = SchedulerProperties + .getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_PASSWORD_VAL); + final String username = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_USERNAME_VAL); + final String password = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_PASSWORD_VAL); + final String environment = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_ENVIRONMENT_VAL); + final String clientAuth = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENTAUTH_VAL); + final String decrypted_client_password = Password.deobfuscate(clientPassword); + String mechAuthString = mechId + ":" + decrypted_client_password; + byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes()); + final String decrypted_password = Password.deobfuscate(password); + String authString = username + ":" + decrypted_password; + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authorization = new String(authEncBytes); + + commonHeaders = new MultivaluedHashMap<String, Object>(); + commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth))); + commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization))); + commonHeaders.put("Environment", Collections.singletonList((Object) (environment))); + + if (client == null) { + + try { + client = HttpBasicClient.getClient(); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, " Unable to get the SSL client", methodname); + + } + } + } + + @SuppressWarnings("unchecked") + public <T> void Get(T t, String sourceId, String path, RestObject<T> restObject) throws Exception { + String methodName = "Get"; + + logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName); + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); + + String url = ""; + restObject.setT(t); + + url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path; + logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url: ", dateFormat.format(new Date()), + methodName, url); + + initRestClient(); + + final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get(); + + int status = cres.getStatus(); + restObject.setStatusCode(status); + + if (status == 200) { + t = (T) cres.readEntity(t.getClass()); + restObject.setT(t); + logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!", + dateFormat.format(new Date()), methodName); + + } else { + throw new Exception(methodName + " with status=" + status + ", url= " + url); + } + + logger.debug(EELFLoggerDelegate.debugLogger, " received status", methodName, status); + + return; + } + + @SuppressWarnings("unchecked") + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) { + + String methodName = "Delete"; + String url = ""; + Response cres = null; + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); + + try { + initRestClient(); + + url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path; + logger.debug(EELFLoggerDelegate.debugLogger, " methodName sending request to: ", + dateFormat.format(new Date()), url, methodName); + + cres = client.target(url).request().accept("application/json").headers(commonHeaders) + // .entity(r) + .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke(); + // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)); + // .delete(Entity.entity(r, MediaType.APPLICATION_JSON)); + + int status = cres.getStatus(); + restObject.setStatusCode(status); + + if (status == 404) { // resource not found + String msg = "Resource does not exist...: " + cres.getStatus(); + logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg); + } else if (status == 200 || status == 204) { + logger.debug(EELFLoggerDelegate.debugLogger, "Resource--deleted:url", dateFormat.format(new Date()), + url); + } else if (status == 202) { + String msg = "Delete in progress: " + status; + logger.debug(EELFLoggerDelegate.debugLogger, "msg ", dateFormat.format(new Date()), msg); + } else { + String msg = "Deleting Resource failed: " + status; + logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg); + } + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.setT(t); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + " HttpClientErrorException:No response entity, this is probably ok, e=", methodName, e); + EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "No response entity, this is probably ok, e=", methodName, + e); + EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); + + } + + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception with the URL", methodName, + url, e); + EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ", + dateFormat.format(new Date()), methodName, url, e); + EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); + + throw e; + + } + } + + @SuppressWarnings("unchecked") + public <T> void post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject) + throws HttpClientErrorException, Exception { + + String methodName = "Post"; + String url = ""; + Response cres = null; + logger.debug(EELFLoggerDelegate.debugLogger, "POST policy rest interface"); + // logRequest (requestDetails); + try { + + initRestClient(); + + url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path; + logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url= ", methodName, url); + // Change the content length + + cres = client.target(url).request().accept("application/json").headers(commonHeaders) + // .header("content-length", 201) + // .header("X-FromAppId", sourceID) + .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); + + /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, + but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which + doesn't work as expected. Created Portal-253 for tracking */ + String str = ((ResponseImpl)cres).readEntity(String.class); + + try { + if(t.getClass().getName().equals(String.class.getName())){ + t=(T) str; + + }else{ + t = (T) gson.fromJson(str, t.getClass()); + } + + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + + //t = (T) cres.readEntity(t.getClass()); + if (t.equals("")) { + restObject.setT(null); + } else { + restObject.setT(t); + } + + int status = cres.getStatus(); + + restObject.setStatusCode(status); + + if (status >= 200 && status <= 299) { + logger.debug(EELFLoggerDelegate.debugLogger, " REST api POST was successful!", methodName); + + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "methodname with Status and URL", methodName, status, url); + } + + } catch (HttpClientErrorException e) { + String message = String.format( + " HttpClientErrorException:Exception with the URL . MethodName: %s, Url: %s", methodName,url); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); + } catch (Exception e) { + String message = String.format( + " Exception with the URL . MethodName: %s, Url: %s", methodName,url); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.BAD_REQUEST.value()); + throw e; + + } + } + + public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException { + return clazz.newInstance(); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxUtil.java b/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxUtil.java new file mode 100644 index 00000000..b3b88b55 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/scheduleraux/SchedulerAuxUtil.java @@ -0,0 +1,82 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.scheduleraux; + +import org.glassfish.jersey.client.ClientResponse; +import org.onap.portal.scheduler.restobjects.RestObject; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class SchedulerAuxUtil { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxUtil.class); + + public static SchedulerAuxResponseWrapper wrapResponse ( String body, int statusCode ) { + + SchedulerAuxResponseWrapper w = new SchedulerAuxResponseWrapper(); + w.setStatus (statusCode); + w.setEntity(body); + + return w; + } + + public static SchedulerAuxResponseWrapper wrapResponse (ClientResponse cres) { + String resp_str = ""; + if ( cres != null ) { + resp_str = cres.readEntity(String.class); + } + int statuscode = cres.getStatus(); + SchedulerAuxResponseWrapper w = SchedulerAuxUtil.wrapResponse ( resp_str, statuscode ); + return (w); + } + + public static SchedulerAuxResponseWrapper wrapResponse (RestObject<String> rs) { + String resp_str = ""; + int status = 0; + if ( rs != null ) { + resp_str = rs.getT(); + status = rs.getStatusCode(); + } + SchedulerAuxResponseWrapper w = SchedulerAuxUtil.wrapResponse ( resp_str, status ); + return (w); + } + + +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/util/CustomJacksonJaxBJsonProvider.java b/portal-BE/src/main/java/org/onap/portal/scheduler/util/CustomJacksonJaxBJsonProvider.java new file mode 100644 index 00000000..e26975e6 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/util/CustomJacksonJaxBJsonProvider.java @@ -0,0 +1,80 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.scheduler.util; + + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; +import javax.ws.rs.ext.Provider; + +@Provider +public class CustomJacksonJaxBJsonProvider extends JacksonJaxbJsonProvider { + + private static ObjectMapper commonMapper = null; + + public CustomJacksonJaxBJsonProvider() { + if (commonMapper == null) { + ObjectMapper mapper = new ObjectMapper(); + + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + mapper.configure(SerializationFeature.INDENT_OUTPUT, false); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); + + mapper.registerModule(new JaxbAnnotationModule()); + + commonMapper = mapper; + } + super.setMapper(commonMapper); + } + + public ObjectMapper getMapper() { + return commonMapper; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/GetTimeSlotsWrapper.java b/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/GetTimeSlotsWrapper.java new file mode 100644 index 00000000..8ebb6217 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/GetTimeSlotsWrapper.java @@ -0,0 +1,42 @@ +/*- + * ============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============================================ + * + * + */ +package org.onap.portal.scheduler.wrapper; + +public class GetTimeSlotsWrapper extends SchedulerResponseWrapper { + +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/PostCreateNewVnfWrapper.java b/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/PostCreateNewVnfWrapper.java new file mode 100644 index 00000000..1e13c4c5 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/PostCreateNewVnfWrapper.java @@ -0,0 +1,82 @@ +/*- + * ============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============================================ + * + * + */ +package org.onap.portal.scheduler.wrapper; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ "uuid" }) +public class PostCreateNewVnfWrapper extends SchedulerResponseWrapper { + + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse() throws JsonProcessingException, IOException { + + Map<String, Object> map = new LinkedHashMap<>(); + map.put("status", getStatus()); + map.put("entity", getEntity()); + map.put("uuid", getUuid()); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonResponse = objectMapper.writeValueAsString(map); + return jsonResponse; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/PostSubmitVnfChangeTimeSlotsWrapper.java b/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/PostSubmitVnfChangeTimeSlotsWrapper.java new file mode 100644 index 00000000..b323b28d --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/PostSubmitVnfChangeTimeSlotsWrapper.java @@ -0,0 +1,82 @@ +/*- + * ============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============================================ + * + * + */ +package org.onap.portal.scheduler.wrapper; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ "uuid" }) +public class PostSubmitVnfChangeTimeSlotsWrapper extends SchedulerResponseWrapper { + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse() throws JsonProcessingException, IOException { + + Map<String, Object> map = new LinkedHashMap<>(); + map.put("status", getStatus()); + map.put("entity", getEntity()); + map.put("uuid", getUuid()); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonResponse = objectMapper.writeValueAsString(map); + return jsonResponse; + + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/SchedulerResponseWrapper.java b/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/SchedulerResponseWrapper.java new file mode 100644 index 00000000..20c828be --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/scheduler/wrapper/SchedulerResponseWrapper.java @@ -0,0 +1,105 @@ +/*- + * ============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============================================ + * + * + */ +package org.onap.portal.scheduler.wrapper; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Scheduler response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ "status", "entity" }) + +public class SchedulerResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse() throws JsonProcessingException, IOException { + /* + * StringBuilder b = new StringBuilder ("{ \"status\": "); + * + * b.append(getStatus()).append(", \"entity\": " + * ).append(this.getEntity()).append("}"); return (b.toString()); + */ + + Map<String, Object> map = new LinkedHashMap<>(); + map.put("status", getStatus()); + map.put("entity", getEntity()); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonResponse = objectMapper.writeValueAsString(map); + return jsonResponse; + + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java index 187e175e..5b721836 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java @@ -92,6 +92,7 @@ import org.onap.portal.domain.dto.transport.Role; import org.onap.portal.domain.dto.transport.RoleInAppForUser; import org.onap.portal.domain.dto.transport.RolesInAppForUser; import org.onap.portal.exception.DeleteDomainObjectFailedException; +import org.onap.portal.exception.RoleFunctionException; import org.onap.portal.exception.SyncUserRolesException; import org.onap.portal.logging.format.EPAppMessagesEnum; import org.onap.portal.logging.logic.EPLogUtil; @@ -127,1752 +128,1799 @@ import org.springframework.web.client.RestTemplate; @Transactional public class AdminRolesService { - private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class); - private static final Object syncRests = new Object(); - private final RestTemplate template = new RestTemplate(); - - private Long SYS_ADMIN_ROLE_ID = 38L; - private final Long ACCOUNT_ADMIN_ROLE_ID = 999L; - private final Long ECOMP_APP_ID = 1L; - private final String ADMIN_ACCOUNT = "Is account admin for user {}"; - - private final AppsCacheService appsCacheService; - private final EntityManager entityManager; - private final FnUserService fnUserService; - private final FnRoleService fnRoleService; - private final FnAppService fnAppService; - private final FnMenuFunctionalService fnMenuFunctionalService; - private final FnUserRoleService fnUserRoleService; - private final EpAppFunctionService epAppFunctionService; - private final EcompUserAppRolesService ecompUserAppRolesService; - private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService; - private final ApplicationsRestClientService applicationsRestClientService; - private final EpUserRolesRequestDetService epUserRolesRequestDetService; - private final ExternalAccessRolesService externalAccessRolesService; - private final EpUserRolesRequestService epUserRolesRequestService; - - @Autowired - public AdminRolesService(AppsCacheService appsCacheService, - final EntityManager entityManager, - final FnUserService fnUserService, FnRoleService fnRoleService, - FnAppService fnAppService, - FnMenuFunctionalService fnMenuFunctionalService, - final FnUserRoleService fnUserRoleService, - EpAppFunctionService epAppFunctionService, - EcompUserAppRolesService ecompUserAppRolesService, - FnMenuFunctionalRolesService fnMenuFunctionalRolesService, - ApplicationsRestClientService applicationsRestClientService, - EpUserRolesRequestDetService epUserRolesRequestDetService, - ExternalAccessRolesService externalAccessRolesService, - EpUserRolesRequestService epUserRolesRequestService) { - this.appsCacheService = appsCacheService; - this.entityManager = entityManager; - this.fnUserService = fnUserService; - this.fnRoleService = fnRoleService; - this.fnAppService = fnAppService; - this.fnMenuFunctionalService = fnMenuFunctionalService; - this.fnUserRoleService = fnUserRoleService; - this.epAppFunctionService = epAppFunctionService; - this.ecompUserAppRolesService = ecompUserAppRolesService; - this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService; - this.applicationsRestClientService = applicationsRestClientService; - this.epUserRolesRequestDetService = epUserRolesRequestDetService; - this.externalAccessRolesService = externalAccessRolesService; - this.epUserRolesRequestService = epUserRolesRequestService; - } - - public boolean isSuperAdmin(final String loginId) { - boolean isSuperAdmin; - try { - isSuperAdmin = fnUserRoleService - .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID); - } catch (Exception e) { - logger.error("isSuperAdmin exception: " + e.toString()); - throw e; + private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class); + private static final Object syncRests = new Object(); + private final RestTemplate template = new RestTemplate(); + + private Long SYS_ADMIN_ROLE_ID = 38L; + private final Long ACCOUNT_ADMIN_ROLE_ID = 999L; + private final Long ECOMP_APP_ID = 1L; + private final String ADMIN_ACCOUNT = "Is account admin for user {}"; + + private final AppsCacheService appsCacheService; + private final EntityManager entityManager; + private final FnUserService fnUserService; + private final FnRoleService fnRoleService; + private final FnAppService fnAppService; + private final FnMenuFunctionalService fnMenuFunctionalService; + private final FnUserRoleService fnUserRoleService; + private final EpAppFunctionService epAppFunctionService; + private final EcompUserAppRolesService ecompUserAppRolesService; + private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService; + private final ApplicationsRestClientService applicationsRestClientService; + private final EpUserRolesRequestDetService epUserRolesRequestDetService; + private final ExternalAccessRolesService externalAccessRolesService; + private final EpUserRolesRequestService epUserRolesRequestService; + + @Autowired + public AdminRolesService(AppsCacheService appsCacheService, + final EntityManager entityManager, + final FnUserService fnUserService, FnRoleService fnRoleService, + FnAppService fnAppService, + FnMenuFunctionalService fnMenuFunctionalService, + final FnUserRoleService fnUserRoleService, + EpAppFunctionService epAppFunctionService, + EcompUserAppRolesService ecompUserAppRolesService, + FnMenuFunctionalRolesService fnMenuFunctionalRolesService, + ApplicationsRestClientService applicationsRestClientService, + EpUserRolesRequestDetService epUserRolesRequestDetService, + ExternalAccessRolesService externalAccessRolesService, + EpUserRolesRequestService epUserRolesRequestService) { + this.appsCacheService = appsCacheService; + this.entityManager = entityManager; + this.fnUserService = fnUserService; + this.fnRoleService = fnRoleService; + this.fnAppService = fnAppService; + this.fnMenuFunctionalService = fnMenuFunctionalService; + this.fnUserRoleService = fnUserRoleService; + this.epAppFunctionService = epAppFunctionService; + this.ecompUserAppRolesService = ecompUserAppRolesService; + this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService; + this.applicationsRestClientService = applicationsRestClientService; + this.epUserRolesRequestDetService = epUserRolesRequestDetService; + this.externalAccessRolesService = externalAccessRolesService; + this.epUserRolesRequestService = epUserRolesRequestService; } - logger.info("isSuperAdmin " + isSuperAdmin); - return isSuperAdmin; - } - - public boolean isAccountAdmin(FnUser user) { - try { - logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId()); - List<Integer> userAdminApps = getAdminAppsForTheUser(user.getId()); - logger.debug(EELFLoggerDelegate.debugLogger, - "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", - user.getOrgUserId(), userAdminApps.size()); - - if (user.getId() != null) { - for (FnUserRole userApp : user.getUserApps()) { - if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || ( - userAdminApps.size() > 1)) { - logger.debug(EELFLoggerDelegate.debugLogger, - "Is account admin for userAdminApps() - for user {}, found Id {}", - user.getOrgUserId(), userApp.getRoleId().getId()); - return true; - } + + public boolean isSuperAdmin(final String loginId) { + boolean isSuperAdmin; + try { + isSuperAdmin = fnUserRoleService + .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID); + } catch (Exception e) { + logger.error("isSuperAdmin exception: " + e.toString()); + throw e; } - } - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while executing isAccountAdmin operation", - e); + logger.info("isSuperAdmin " + isSuperAdmin); + return isSuperAdmin; } - return false; - } - - public boolean isUser(FnUser user) { - try { - FnUser currentUser = fnUserService.getUser(user.getId()).orElseThrow(Exception::new); - if (currentUser != null && currentUser.getId() != null) { - for (FnUserRole userApp : currentUser.getUserApps()) { - if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) { - FnRole role = userApp.getRoleId(); - if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId() - .equals(ACCOUNT_ADMIN_ROLE_ID)) { - if (role.getActiveYn()) { - return true; - } + + public boolean isAccountAdmin(final long userId, final String orgUserId, final Set<FnUserRole> userApps) { + try { + logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId); + List<Integer> userAdminApps = getAdminAppsForTheUser(userId); + logger.debug(EELFLoggerDelegate.debugLogger, + "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", + orgUserId, userAdminApps.size()); + + for (FnUserRole userApp : userApps) { + if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || ( + userAdminApps.size() > 1)) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Is account admin for userAdminApps() - for user {}, found Id {}", + orgUserId, userApp.getRoleId().getId()); + return true; + } } - } - } - } - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", - e); - } - return false; - } - - public boolean isRoleAdmin(Long userId) { - try { - logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access"); - List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId); - logger.debug(EELFLoggerDelegate.debugLogger, - "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser); - Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser); - Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>(); - Set<String> roleFunSet; - roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")) - .collect(Collectors.toSet()); - if (!roleFunSet.isEmpty()) { - for (String roleFunction : roleFunSet) { - String type = externalAccessRolesService.getFunctionCodeType(roleFunction); - getRoleFuncListOfPortalSet1.add(type); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isAccountAdmin operation", + e); } - } - - boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream() - .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver")); - logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction", - checkIfFunctionsExits); - - return checkIfFunctionsExits; - - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while executing isRoleAdmin operation", - e); - } - return false; - } - - private boolean isAccountAdminOfApplication(Long userId, FnApp app) { - boolean isApplicationAccountAdmin = false; - try { - logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId); - List<Integer> userAdminApps = getAdminAppsForTheUser(userId); - if (!userAdminApps.isEmpty()) { - isApplicationAccountAdmin = userAdminApps.contains(app.getId()); - logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId, - app.getId()); - } - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while executing isAccountAdminOfApplication operation", e); + return false; } - logger.debug(EELFLoggerDelegate.debugLogger, - "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin, - userId); - return isApplicationAccountAdmin; - - } - - private List<Integer> getAdminAppsForTheUser(final Long userId) { - String query = "select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 and (fa.enabled = 'Y' || fa.app_id=1)"; - return entityManager.createQuery(query, Integer.class) - .setParameter("userId", userId).getResultList(); - } - - public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user, - AppWithRolesForUser newAppRolesForUser) { - boolean result = false; - boolean epRequestValue = false; - String userId = ""; - String reqMessage = ""; - if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) { - userId = newAppRolesForUser.getOrgUserId().trim(); - } - Long appId = newAppRolesForUser.getAppId(); - List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles(); - - if (userId.length() > 0) { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - try { - FnApp app = fnAppService.getById(appId); - - boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(), - app); - Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>(); - - boolean checkIfUserIsOnlyRoleAdmin = - isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin; - if (checkIfUserIsOnlyRoleAdmin) { - for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { - if (!roleInAppForUser.getIsApplied()) { - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(roleInAppForUser.getRoleId()); - ecompRole.setName(roleInAppForUser.getRoleName()); - rolesGotDeletedFromApprover.add(ecompRole); + public boolean isUser(final long userId) { + try { + FnUser currentUser = fnUserService.getUser(userId).orElseThrow(Exception::new); + if (currentUser != null && currentUser.getId() != null) { + for (FnUserRole userApp : currentUser.getUserApps()) { + if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) { + FnRole role = userApp.getRoleId(); + if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId() + .equals(ACCOUNT_ADMIN_ROLE_ID)) { + if (role.getActiveYn()) { + return true; + } + } + } + } } - } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", + e); } + return false; + } - applyChangesToUserAppRolesForMyLoginsRequest(user, appId); - - boolean systemUser = newAppRolesForUser.isSystemUser(); - - if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) - && systemUser) { - - Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList); - RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, - userRolesInLocalApp); - List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles(); - Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>(); - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - // Apply changes in external Access system - - updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), - roleAppUserList, - epRequestValue, systemUser, rolesGotDeletedByApprover, false); - } - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, - "Portal", - systemUser, rolesGotDeletedByApprover, false); - - } else if (!app.getAuthCentral() && systemUser) { - throw new Exception("For non-centralized application we cannot add systemUser"); - } else { // if centralized app - if (app.getAuthCentral()) { - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - pushRemoteUser(roleInAppForUserList, userId, app, mapper, - applicationsRestClientService, false); + public boolean isRoleAdmin(Long userId) { + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access"); + List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId); + logger.debug(EELFLoggerDelegate.debugLogger, + "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser); + Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser); + Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>(); + Set<String> roleFunSet; + roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")) + .collect(Collectors.toSet()); + if (!roleFunSet.isEmpty()) { + for (String roleFunction : roleFunSet) { + String type = externalAccessRolesService.getFunctionCodeType(roleFunction); + getRoleFuncListOfPortalSet1.add(type); + } } - Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp( - roleInAppForUserList); - RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, - appId, - userRolesInLocalApp); - List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles(); - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream() + .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver")); + logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction", + checkIfFunctionsExits); - // Apply changes in external Access system - updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), - roleAppUserList, - epRequestValue, false, rolesGotDeletedFromApprover, - checkIfUserIsOnlyRoleAdmin); - } - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, - epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover, - checkIfUserIsOnlyRoleAdmin); - } - // In case if portal is not centralized then follow existing approach - else if (!app.getAuthCentral() && app.getId() - .equals(PortalConstants.PORTAL_APP_ID)) { - Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp( - roleInAppForUserList); - RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, - appId, - userRolesInLocalApp); - Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>(); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, - epRequestValue, "Portal", false, rolesGotDeletedByApprover, false); - } else {// remote app - FnUser remoteAppUser; - if (!app.getAuthCentral() && !app.getId() - .equals(PortalConstants.PORTAL_APP_ID)) { - - remoteAppUser = checkIfRemoteUserExits(userId, app, - applicationsRestClientService); - - if (remoteAppUser == null) { - addRemoteUser(roleInAppForUserList, userId, app, - mapper, applicationsRestClientService); - } - Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp( - roleInAppForUserList, mapper, - applicationsRestClientService, appId, userId); - RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate( - userId, appId, - userRolesInRemoteApp); - Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>(); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, - epRequestValue, null, false, rolesGotDeletedByApprover, false); - - // If no roles remain, request app to set user inactive. - if (userRolesInRemoteApp.size() == 0) { - logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", - app, - userId); - postUserToRemoteApp(userId, app, - applicationsRestClientService); - } - } - } + return checkIfFunctionsExits; + + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isRoleAdmin operation", + e); } - } catch (Exception e) { - String message = String.format( - "Failed to create user or update user roles for User %s, AppId %s", - userId, Long.toString(appId)); - logger.error(EELFLoggerDelegate.errorLogger, message, e); - result = false; - reqMessage = e.getMessage(); - } + return false; } - //return result; - return new ExternalRequestFieldsValidator(result, reqMessage); - } + private boolean isAccountAdminOfApplication(Long userId, FnApp app) { + boolean isApplicationAccountAdmin = false; + try { + logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId); + List<Integer> userAdminApps = getAdminAppsForTheUser(userId); + if (!userAdminApps.isEmpty()) { + isApplicationAccountAdmin = userAdminApps.contains(app.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId, + app.getId()); + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isAccountAdminOfApplication operation", e); + } + logger.debug(EELFLoggerDelegate.debugLogger, + "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin, + userId); + return isApplicationAccountAdmin; - private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app, - ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed) - throws Exception { - pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper, - roleInAppForUserList, appRoleIdUsed); - } + } + private List<Integer> getAdminAppsForTheUser(final Long userId) { + String query = "select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 and (fa.enabled = 'Y' || fa.app_id=1)"; + return entityManager.createQuery(query, Integer.class) + .setParameter("userId", userId).getResultList(); + } - private void postUserToRemoteApp(String userId, FnApp app, - ApplicationsRestClientService applicationsRestClientService) throws HTTPException { + public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user, + AppWithRolesForUser newAppRolesForUser) { + boolean result = false; + boolean epRequestValue = false; + String userId = ""; + String reqMessage = ""; + if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) { + userId = newAppRolesForUser.getOrgUserId().trim(); + } + Long appId = newAppRolesForUser.getAppId(); + List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles(); - getUser(userId, app, applicationsRestClientService); + if (userId.length() > 0) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - } + try { + FnApp app = fnAppService.getById(appId); + + boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(), + app); + Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>(); + + boolean checkIfUserIsOnlyRoleAdmin = + isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin; + if (checkIfUserIsOnlyRoleAdmin) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (!roleInAppForUser.getIsApplied()) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.getRoleId()); + ecompRole.setName(roleInAppForUser.getRoleName()); + rolesGotDeletedFromApprover.add(ecompRole); + } + } + } - private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService) - throws HTTPException { - return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true); + applyChangesToUserAppRolesForMyLoginsRequest(user, appId); - } + boolean systemUser = newAppRolesForUser.isSystemUser(); - private void pushUserOnRemoteApp(String userId, FnApp app, - ApplicationsRestClientService applicationsRestClientService, - ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed) - throws Exception { + if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) + && systemUser) { - FnUser client; - client = fnUserService.loadUserByUsername(userId); + Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInLocalApp); + List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles(); + Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>(); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + // Apply changes in external Access system - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - if (client == null) { - String msg = "cannot create user " + userId + ", because he/she cannot be found in directory."; - logger.error(EELFLoggerDelegate.errorLogger, msg); - List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId); - if (!userList.isEmpty()) { - logger.debug(EELFLoggerDelegate.debugLogger, - userList.get(0).getOrgUserId() + " User was found in Portal"); - client = userList.get(0); - client.setUserApps(Collections.EMPTY_SET); - client.setIsSystemUser(false); - } else { - logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal"); - throw new Exception(msg); - } + updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), + roleAppUserList, + epRequestValue, systemUser, rolesGotDeletedByApprover, false); + } + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, + "Portal", + systemUser, rolesGotDeletedByApprover, false); + + } else if (!app.getAuthCentral() && systemUser) { + throw new Exception("For non-centralized application we cannot add systemUser"); + } else { // if centralized app + if (app.getAuthCentral()) { + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + pushRemoteUser(roleInAppForUserList, userId, app, mapper, + applicationsRestClientService, false); + } + + Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp( + roleInAppForUserList); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, + appId, + userRolesInLocalApp); + List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles(); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), + roleAppUserList, + epRequestValue, false, rolesGotDeletedFromApprover, + checkIfUserIsOnlyRoleAdmin); + } + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, + epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover, + checkIfUserIsOnlyRoleAdmin); + } + // In case if portal is not centralized then follow existing approach + else if (!app.getAuthCentral() && app.getId() + .equals(PortalConstants.PORTAL_APP_ID)) { + Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp( + roleInAppForUserList); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, + appId, + userRolesInLocalApp); + Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>(); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, + epRequestValue, "Portal", false, rolesGotDeletedByApprover, false); + } else {// remote app + FnUser remoteAppUser; + if (!app.getAuthCentral() && !app.getId() + .equals(PortalConstants.PORTAL_APP_ID)) { + + remoteAppUser = checkIfRemoteUserExits(userId, app, + applicationsRestClientService); + + if (remoteAppUser == null) { + addRemoteUser(roleInAppForUserList, userId, app, + mapper, applicationsRestClientService); + } + Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp( + roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate( + userId, appId, + userRolesInRemoteApp); + Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>(); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, + epRequestValue, null, false, rolesGotDeletedByApprover, false); + + // If no roles remain, request app to set user inactive. + if (userRolesInRemoteApp.size() == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", + app, + userId); + postUserToRemoteApp(userId, app, + applicationsRestClientService); + } + } + } + } + } catch (Exception e) { + String message = String.format( + "Failed to create user or update user roles for User %s, AppId %s", + userId, Long.toString(appId)); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + result = false; + reqMessage = e.getMessage(); + } + } + return new ExternalRequestFieldsValidator(result, reqMessage); } - client.setLoginId(userId); - client.setActiveYn(true); - client.setOrgUserId(userId); + private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app, + ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed) + throws Exception { + pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper, + roleInAppForUserList, appRoleIdUsed); + } - roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false)); - SortedSet<Role> roles = new TreeSet<>(); - List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId()); - List<FnApp> appList = new ArrayList<>(); - appList.add(app); - List<CentralV2Role> roleList = new ArrayList<>(); + private void postUserToRemoteApp(String userId, FnApp app, + ApplicationsRestClientService applicationsRestClientService) throws HTTPException { - List<FnRole> userRoles = new ArrayList<>(); + getUser(userId, app, applicationsRestClientService); - for (RoleInAppForUser roleInappForUser : roleInAppForUserList) { - FnRole role = new FnRole(); - role.setId(roleInappForUser.getRoleId()); - role.setRoleName(roleInappForUser.getRoleName()); - userRoles.add(role); } - if (appRoleIdUsed) { - List<FnRole> userAppRoles = new ArrayList<>(); - for (FnRole role : userRoles) { - FnRole appRole = getAppRoles.stream() - .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny() - .orElse(null); - FnRole epRole = new FnRole(); - if (appRole != null) { - epRole.setId(appRole.getId()); - epRole.setRoleName(appRole.getRoleName()); - } - userAppRoles.add(epRole); - } - userRoles = new ArrayList<>(userAppRoles); - } - roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList); - - for (CentralV2Role epRole : roleList) { - Role role = new Role(); - FnRole appRole = getAppRoles.stream() - .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null); - if (appRole != null) { - role.setId(appRole.getAppRoleId()); - role.setRoleName(epRole.getName()); - role.setFnRoleFunctions(epRole.getRoleFunctions()); - } - roles.add(role); - } - client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet())); - String userInString; - userInString = mapper.writerFor(FnUser.class).writeValueAsString(client); - logger.debug(EELFLoggerDelegate.debugLogger, - "about to post a client to remote application, users json = " + userInString); - applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId)); - } - - private FnRole roleToFnRole(Role role) { - return FnRole.builder() - .id(role.getId()) - .roleName(role.getRoleName()) - .activeYn(role.getActiveYn()) - .priority(role.getPriority()) - .fnRoleFunctions(role.getFnRoleFunctions()) - .childRoles(role.getChildRoles()) - .parentRoles(role.getParentRoles()) - .build(); - } - - private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper, - ApplicationsRestClientService applicationsRestClientService, Long appId, String userId) - throws JsonProcessingException, HTTPException { - Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList); - Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList); - String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote); - FnApp externalApp; - externalApp = appsCacheService.getApp(appId); - String appBaseUri = null; - Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>(); - if (externalApp != null) { - appBaseUri = externalApp.getAppRestEndpoint(); - } - if (appBaseUri != null && appBaseUri.endsWith("/api")) { - for (EcompRole eprole : updatedUserRolesinRemote) { - RemoteRoleV1 role = new RemoteRoleV1(); - role.setId(eprole.getId()); - role.setName(eprole.getName()); - updatedUserRolesinRemoteV1.add(role); - } - userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1); - } - applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, - String.format("/user/%s/roles", userId)); - return updateUserRolesInEcomp; - } - - private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app, - ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception { - if (remoteUserShouldBeCreated(roleInAppForUserList)) { - createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper); + private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService) + throws HTTPException { + return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true); + } - } - private void createNewUserOnRemoteApp(String userId, FnApp app, - ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper) - throws Exception { + private void pushUserOnRemoteApp(String userId, FnApp app, + ApplicationsRestClientService applicationsRestClientService, + ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed) + throws Exception { - FnUser client = fnUserService.loadUserByUsername(userId); + FnUser client; + client = fnUserService.loadUserByUsername(userId); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + if (client == null) { + String msg = "cannot create user " + userId + ", because he/she cannot be found in directory."; + logger.error(EELFLoggerDelegate.errorLogger, msg); + List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId); + if (!userList.isEmpty()) { + logger.debug(EELFLoggerDelegate.debugLogger, + userList.get(0).getOrgUserId() + " User was found in Portal"); + client = userList.get(0); + client.setUserApps(Collections.EMPTY_SET); + client.setIsSystemUser(false); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal"); + throw new Exception(msg); + } - if (client == null) { - String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook."; - logger.error(EELFLoggerDelegate.errorLogger, msg); - throw new Exception(msg); - } + } - client.setLoginId(userId); - client.setActiveYn(true); + client.setLoginId(userId); + client.setActiveYn(true); + client.setOrgUserId(userId); - String userInString; - userInString = mapper.writerFor(FnUser.class).writeValueAsString(client); - logger.debug(EELFLoggerDelegate.debugLogger, - "about to post new client to remote application, users json = " + userInString); - applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId)); + roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false)); + SortedSet<Role> roles = new TreeSet<>(); - } + List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId()); + List<FnApp> appList = new ArrayList<>(); + appList.add(app); + List<CentralV2Role> roleList = new ArrayList<>(); - private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) { - for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { - if (roleInAppForUser.getIsApplied()) { - return true; - } - } - return false; - } - - private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) { - Set<EcompRole> existingUserRoles = new TreeSet<>(); - for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { - if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId() - .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) { - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(roleInAppForUser.getRoleId()); - ecompRole.setName(roleInAppForUser.getRoleName()); - existingUserRoles.add(ecompRole); - } - } - return existingUserRoles; - } - - private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) { - List<EpUserRolesRequest> epRequestIdVal; - try { - epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId); - if (epRequestIdVal.size() > 0) { - EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0); - epAppRolesRequestData.setUpdatedDate(LocalDateTime.now()); - epAppRolesRequestData.setRequestStatus("O"); - epAppRolesRequestData.setUserId(user); - epUserRolesRequestService.saveOne(epAppRolesRequestData); - List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService - .appRolesRequestDetailList(epAppRolesRequestData.getReqId()); - if (epUserAppRolesDetailList.size() > 0) { - for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) { - epRequestUpdateList.setRequestType("O"); - epRequestUpdateList.setReqId(epAppRolesRequestData); - epRequestUpdateList.setReqId(epAppRolesRequestData); - epUserRolesRequestDetService.saveOne(epRequestUpdateList); - } - logger.debug(EELFLoggerDelegate.debugLogger, - "User App roles request from User Page is overridden"); + List<FnRole> userRoles = new ArrayList<>(); + + for (RoleInAppForUser roleInappForUser : roleInAppForUserList) { + FnRole role = new FnRole(); + role.setId(roleInappForUser.getRoleId()); + role.setRoleName(roleInappForUser.getRoleName()); + userRoles.add(role); } - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e); - } - } - - private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) { - return constructUsersEcompRoles(roleInAppForUserList); - } - - private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) { - Set<EcompRole> existingUserRoles = new TreeSet<>(); - for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { - if (roleInAppForUser.getIsApplied()) { - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(roleInAppForUser.getRoleId()); - ecompRole.setName(roleInAppForUser.getRoleName()); - existingUserRoles.add(ecompRole); - } - } - return existingUserRoles; - } - - public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId, - Set<EcompRole> userRolesInRemoteApp) { - RolesInAppForUser result; - result = new RolesInAppForUser(); - result.setAppId(appId); - result.setOrgUserId(userId); - - for (EcompRole role : userRolesInRemoteApp) { - RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); - roleInAppForUser.setRoleId(role.getId()); - roleInAppForUser.setRoleName(role.getName()); - roleInAppForUser.setIsApplied(true); - result.getRoles().add(roleInAppForUser); - } - return result; - } - - private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, - boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover, - boolean isLoggedInUserRoleAdminofApp) throws Exception { - try { - List<FnUser> userInfo = checkIfUserExists(orgUserId); - if (userInfo.isEmpty()) { - createLocalUserIfNecessary(orgUserId, isSystemUser); - } - String name; - if (EPCommonSystemProperties - .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) - && !isSystemUser) { - name = orgUserId - + SystemProperties - .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); - } else { - name = orgUserId; - } - ObjectMapper mapper = new ObjectMapper(); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers); - ResponseEntity<String> getResponse = externalAccessRolesService - .getUserRolesFromExtAuthSystem(name, getUserRolesEntity); - - List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>(); - String res = getResponse.getBody(); - JSONObject jsonObj; - JSONArray extRoles = null; - if (!res.equals("{}")) { - jsonObj = new JSONObject(res); - extRoles = jsonObj.getJSONArray("role"); - } - ExternalAccessUserRoleDetail userRoleDetail; - if (extRoles != null) { - for (int i = 0; i < extRoles.length(); i++) { - if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".") - && !extRoles.getJSONObject(i).getString("name") - .equals(app.getAuthNamespace() + ".admin") - && !extRoles.getJSONObject(i).getString("name") - .equals(app.getAuthNamespace() + ".owner")) { - if (extRoles.getJSONObject(i).has("description")) { - ExternalRoleDescription desc = new ExternalRoleDescription( - extRoles.getJSONObject(i).getString("description")); - 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); + if (appRoleIdUsed) { + List<FnRole> userAppRoles = new ArrayList<>(); + for (FnRole role : userRoles) { + FnRole appRole = getAppRoles.stream() + .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny() + .orElse(null); + FnRole epRole = new FnRole(); + if (appRole != null) { + epRole.setId(appRole.getId()); + epRole.setRoleName(appRole.getRoleName()); + } + userAppRoles.add(epRole); } - - } + userRoles = new ArrayList<>(userAppRoles); } - } - - List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList( - userRoleDetailList, app); - - List<EcompUserAppRoles> userAppList; - // 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) { - FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0); - userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId()); - 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); + roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList); + + for (CentralV2Role epRole : roleList) { + Role role = new Role(); + FnRole appRole = getAppRoles.stream() + .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null); + if (appRole != null) { + role.setId(appRole.getAppRoleId()); + role.setRoleName(epRole.getName()); + role.setFnRoleFunctions(epRole.getRoleFunctions()); } - } + roles.add(role); } - } - List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct() - .collect(Collectors.toList()); - Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>(); - for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) { - currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, - "_"), roleInAppUserNew); - } - final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>(); - for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) { - currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole); - } - - if (isLoggedInUserRoleAdminofApp) { - if (deletedRolesByApprover.size() > 0) { - List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>(); - for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) { - for (EcompRole role : deletedRolesByApprover) { - if ((userRole.getName().substring(app.getAuthNamespace().length() + 1)) - .equals(role.getName())) { - newUpdatedRoles.add(userRole); - } - } - } - if (newUpdatedRoles.size() > 0) { - userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles); - } else { - userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); - currentUserRolesToUpdate = new HashMap<>(); - - } + client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet())); + String userInString; + userInString = mapper.writerFor(FnUser.class).writeValueAsString(client); + logger.debug(EELFLoggerDelegate.debugLogger, + "about to post a client to remote application, users json = " + userInString); + applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId)); + } - } else { - userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); - currentUserRolesToUpdate = new HashMap<>(); + private FnRole roleToFnRole(Role role) { + return FnRole.builder() + .id(role.getId()) + .roleName(role.getRoleName()) + .activeYn(role.getActiveYn()) + .priority(role.getPriority()) + .fnRoleFunctions(role.getFnRoleFunctions()) + .childRoles(role.getChildRoles()) + .parentRoles(role.getParentRoles()) + .build(); + } + private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper, + ApplicationsRestClientService applicationsRestClientService, Long appId, String userId) + throws JsonProcessingException, HTTPException { + Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList); + Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList); + String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote); + FnApp externalApp; + externalApp = appsCacheService.getApp(appId); + String appBaseUri = null; + Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>(); + if (externalApp != null) { + appBaseUri = externalApp.getAppRestEndpoint(); } - } - - // Check if user roles does not exists in local but still there in External Central Auth System delete them all - for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) { - if (!(currentUserRolesToUpdate - .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) { - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, - "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}", - userRole.getName()); - 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.getName(), deleteResponse.getBody()); - } - } - // Check if user roles does not exists in External Central Auth System add them all - for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) { - if (!(currentUserRolesInExternalSystem - .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll( - EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, - "_")))) { - ExternalAccessUser extUser = new ExternalAccessUser(name, - app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll( - EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, - "_")); - String formattedUserRole = mapper.writeValueAsString(extUser); - HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, - "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}", - name, addUserRole.getRoleName()); - ResponseEntity<String> addResponse = template - .exchange(SystemProperties - .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "userRole", HttpMethod.POST, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, - "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}", - addResponse.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", - addResponse.getBody(), - addUserRole.getRoleName()); - throw new Exception(addResponse.getBody()); - } + if (appBaseUri != null && appBaseUri.endsWith("/api")) { + for (EcompRole eprole : updatedUserRolesinRemote) { + RemoteRoleV1 role = new RemoteRoleV1(); + role.setId(eprole.getId()); + role.setName(eprole.getName()); + updatedUserRolesinRemoteV1.add(role); + } + userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1); } - } - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, - "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", - app.getId(), e); - if (e.getStatusCode() == HttpStatus.FORBIDDEN) { - logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", - orgUserId); - throw new HttpClientErrorException(HttpStatus.FORBIDDEN, - "Please enter the valid systemUser"); - } - if (e.getStatusCode() == HttpStatus.NOT_FOUND) { - logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role"); - throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role"); - } - EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST); - throw e; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", - app.getId(), e); - EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST); - throw e; + applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, + String.format("/user/%s/roles", userId)); + return updateUserRolesInEcomp; } - } - - private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList( - List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) { - Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app); - //Add Account Admin role for partner app to prevent conflict - if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) { - FnRole role = new FnRole(); - role.setRoleName(PortalConstants.ADMIN_ROLE - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - epRoleList.put(role.getRoleName(), role); - } - userRoleDetailList.removeIf( - userRoleDetail -> !epRoleList - .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1))); - return userRoleDetailList; - } - - private List<FnUser> checkIfUserExists(String userParams) { - return fnUserService.getUserWithOrgUserId(userParams); - } - - @Transactional - private void createLocalUserIfNecessary(String userId, boolean isSystemUser) { - if (StringUtils.isEmpty(userId)) { - logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!"); - return; - } - try { - List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId); - if (userList.size() == 0) { - FnUser client; - if (!isSystemUser) { - client = fnUserService.loadUserByUsername(userId); - } else { - client = new FnUser(); - client.setOrgUserId(userId); - client.setIsSystemUser(true); - client.setFirstName(userId.substring(0, userId.indexOf("@"))); + + private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app, + ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception { + if (remoteUserShouldBeCreated(roleInAppForUserList)) { + createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper); } + } + + private void createNewUserOnRemoteApp(String userId, FnApp app, + ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper) + throws Exception { + + FnUser client = fnUserService.loadUserByUsername(userId); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + if (client == null) { - String msg = "createLocalUserIfNecessary: cannot create user " + userId - + ", because not found in phonebook"; - logger.error(EELFLoggerDelegate.errorLogger, msg); - } else { - client.setLoginId(userId); - client.setActiveYn(true); + String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook."; + logger.error(EELFLoggerDelegate.errorLogger, msg); + throw new Exception(msg); } - fnUserService.saveFnUser(client); - } - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - } - } + client.setLoginId(userId); + client.setActiveYn(true); - private FnUser checkIfRemoteUserExits(String userId, FnApp app, - ApplicationsRestClientService applicationsRestClientService) throws HTTPException { - FnUser checkRemoteUser = null; - try { - checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService); - } catch (HTTPException e) { - // Some apps are returning 400 if user is not found. - if (e.getResponseCode() == 400) { - logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", - e); - } else if (e.getResponseCode() == 404) { + String userInString; + userInString = mapper.writerFor(FnUser.class).writeValueAsString(client); logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing", - e); - } else { - // Other response code, let it come thru. - throw e; - } - } - return checkRemoteUser; - } - - private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService) - throws HTTPException { - if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) { - List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId); - if (userList != null && !userList.isEmpty()) { - return userList.get(0); - } else { - return null; - } + "about to post new client to remote application, users json = " + userInString); + applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId)); + } - return getUser(userId, app, applicationsRestClientService); - } - - private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, - boolean externalSystemRequest, String reqType, boolean isSystemUser, - Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception { - boolean result = false; - String userId = rolesInAppForUser.getOrgUserId(); - Long appId = rolesInAppForUser.getAppId(); - synchronized (syncRests) { - createLocalUserIfNecessary(userId, isSystemUser); - - EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()]; - for (int i = 0; - i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) { - RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i); - EcompRole role = new EcompRole(); - role.setId(roleInAppForUser.getRoleId()); - role.setName(roleInAppForUser.getRoleName()); - userAppRoles[i] = role; - } - try { - EcompRole[] applicationRoles = null; - - if (isLoggedInUserRoleAdminOfApp) { - List<EcompRole> roles = Arrays.stream(userAppRoles) - .collect(Collectors.toList()); - List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover); - roles.addAll(roles1); - applicationRoles = roles.toArray(new EcompRole[0]); - } - syncUserRoles(userId, appId, userAppRoles, externalSystemRequest, - reqType, isLoggedInUserRoleAdminOfApp, applicationRoles); - result = true; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " - + userId, e); - if ("DELETE".equals(reqType)) { - throw new Exception(e.getMessage()); + private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.getIsApplied()) { + return true; + } } - } + return false; } - return result; - } - - private void syncUserRoles(String userId, Long appId, - EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin, - EcompRole[] appRoles) throws Exception { - - Transaction transaction = null; - String roleActive; - HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles); - List<FnRole> roleInfo = externalAccessRolesService - .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); - FnRole adminRole = new FnRole(); - if (roleInfo.size() > 0) { - adminRole = roleInfo.get(0); - logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName()); - } - try { - List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId); - if (userList.size() > 0) { - FnUser client = userList.get(0); - roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'"; - List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId); - entityManager - .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive) - .setParameter("appId", appId) - .setParameter("userId", client.getId()) - .getResultList(); - - if ("DELETE".equals(reqType)) { - for (FnUserRole userAppRoleList : userRoles) { - List<FnRole> rolesList = - (!userAppRoleList.getRoleId().getRoleName() - .equals(adminRole.getRoleName())) - ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId - (userAppRoleList.getRoleId().getRoleName(), appId) - : fnRoleService.retrieveAppRolesWhereAppIdIsNull(); - if (!rolesList.isEmpty()) { - checkIfRoleInactive(rolesList.get(0)); + + private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) { + Set<EcompRole> existingUserRoles = new TreeSet<>(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId() + .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.getRoleId()); + ecompRole.setName(roleInAppForUser.getRoleName()); + existingUserRoles.add(ecompRole); } - } } + return existingUserRoles; + } - if (appRoles != null) { - List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList()); - List<FnUserRole> finalUserRolesList = new ArrayList<>(); - if (checkIfUserisRoleAdmin) { - for (EcompRole role : appRolesList) { - for (FnUserRole userAppRoleList : userRoles) { - if (userAppRoleList.getRoleId().getRoleName() - .equals(role.getName())) { - finalUserRolesList.add(userAppRoleList); + private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) { + List<EpUserRolesRequest> epRequestIdVal; + try { + epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId); + if (epRequestIdVal.size() > 0) { + EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0); + epAppRolesRequestData.setUpdatedDate(LocalDateTime.now()); + epAppRolesRequestData.setRequestStatus("O"); + epAppRolesRequestData.setUserId(user); + epUserRolesRequestService.saveOne(epAppRolesRequestData); + List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService + .appRolesRequestDetailList(epAppRolesRequestData.getReqId()); + if (epUserAppRolesDetailList.size() > 0) { + for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) { + epRequestUpdateList.setRequestType("O"); + epRequestUpdateList.setReqId(epAppRolesRequestData); + epRequestUpdateList.setReqId(epAppRolesRequestData); + epUserRolesRequestDetService.saveOne(epRequestUpdateList); + } + logger.debug(EELFLoggerDelegate.debugLogger, + "User App roles request from User Page is overridden"); } + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e); + } + } - } + private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) { + return constructUsersEcompRoles(roleInAppForUserList); + } + + private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) { + Set<EcompRole> existingUserRoles = new TreeSet<>(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.getIsApplied()) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.getRoleId()); + ecompRole.setName(roleInAppForUser.getRoleName()); + existingUserRoles.add(ecompRole); } - userRoles = new ArrayList<>(finalUserRolesList); - } } + return existingUserRoles; + } - for (FnUserRole userRole : userRoles) { - if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId()) - && !PortalConstants.SYS_ADMIN_ROLE_ID - .equals(userRole.getRoleId().getId()) - && !extRequestValue) { - syncUserRolesExtension(userRole, appId, - newUserAppRolesMap); - } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) - || "DELETE".equals(reqType))) { - syncUserRolesExtension(userRole, appId, - newUserAppRolesMap); - } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID - .equals(userRole.getRoleId().getId())) { - syncUserRolesExtension(userRole, appId, - newUserAppRolesMap); - } + public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId, + Set<EcompRole> userRolesInRemoteApp) { + RolesInAppForUser result; + result = new RolesInAppForUser(); + result.setAppId(appId); + result.setOrgUserId(userId); + + for (EcompRole role : userRolesInRemoteApp) { + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.setRoleId(role.getId()); + roleInAppForUser.setRoleName(role.getName()); + roleInAppForUser.setIsApplied(true); + result.getRoles().add(roleInAppForUser); } + return result; + } - Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values(); - if (newRolesToAdd.size() > 0) { - FnApp app = fnAppService.getById(appId); + private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, + boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover, + boolean isLoggedInUserRoleAdminofApp) throws Exception { + try { + List<FnUser> userInfo = checkIfUserExists(orgUserId); + if (userInfo.isEmpty()) { + createLocalUserIfNecessary(orgUserId, isSystemUser); + } + String name; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) + && !isSystemUser) { + name = orgUserId + + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } else { + name = orgUserId; + } + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers); + ResponseEntity<String> getResponse = externalAccessRolesService + .getUserRolesFromExtAuthSystem(name, getUserRolesEntity); + + List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>(); + String res = getResponse.getBody(); + JSONObject jsonObj; + JSONArray extRoles = null; + if (!res.equals("{}")) { + jsonObj = new JSONObject(res); + extRoles = jsonObj.getJSONArray("role"); + } + ExternalAccessUserRoleDetail userRoleDetail; + if (extRoles != null) { + for (int i = 0; i < extRoles.length(); i++) { + if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".") + && !extRoles.getJSONObject(i).getString("name") + .equals(app.getAuthNamespace() + ".admin") + && !extRoles.getJSONObject(i).getString("name") + .equals(app.getAuthNamespace() + ".owner")) { + if (extRoles.getJSONObject(i).has("description")) { + ExternalRoleDescription desc = new ExternalRoleDescription( + extRoles.getJSONObject(i).getString("description")); + 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); + } - HashMap<Long, FnRole> rolesMap = new HashMap<>(); - if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app - String appIdValue = ""; - if (!extRequestValue) { - appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID; + } + } } - @SuppressWarnings("unchecked") - List<FnRole> roles = entityManager - .createQuery( - "from " + FnRole.class.getName() + " where appId is null " - + appIdValue).getResultList(); - for (FnRole role : roles) { - role.setAppId(1L); - rolesMap.put(role.getId(), role); + + List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList( + userRoleDetailList, app); + + List<EcompUserAppRoles> userAppList; + // 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) { + FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0); + userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId()); + 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); + } + } + } } - } else { // remote app - @SuppressWarnings("unchecked") - List<FnRole> roles = entityManager - .createQuery("from EPRole where appId=:appId") - .setParameter("appId", appId) - .getResultList(); - for (FnRole role : roles) { - if (!extRequestValue && app.getAuthCentral()) { - rolesMap.put(role.getId(), role); - } else { - rolesMap.put(role.getAppRoleId(), role); - } + List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct() + .collect(Collectors.toList()); + Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>(); + for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) { + currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_"), roleInAppUserNew); } - } - - FnRole role; - for (EcompRole userRole : newRolesToAdd) { - FnUserRole userApp = new FnUserRole(); - if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName() - .equals(adminRole.getRoleName())) { - role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); - userApp.setRoleId(role); - } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) - && !extRequestValue) { - continue; - } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app - .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) { - continue; - } else { - userApp.setRoleId(rolesMap.get(userRole.getId())); + final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>(); + for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) { + currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole); } - userApp.setUserId(client); - userApp.setFnAppId(app); - fnUserRoleService.saveOne(userApp); - } - - if (PortalConstants.PORTAL_APP_ID.equals(appId)) { - /* - * for local app -- hack - always make sure fn_role - * table's app_id is null and not 1 for primary app in - * this case being onap portal app; reason: hibernate - * is rightly setting this to 1 while persisting to - * fn_role as per the mapping but SDK role management - * code expects the app_id to be null as there is no - * concept of App_id in SDK - */ - Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 "); - query.executeUpdate(); - } + if (isLoggedInUserRoleAdminofApp) { + if (deletedRolesByApprover.size() > 0) { + List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>(); + for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) { + for (EcompRole role : deletedRolesByApprover) { + if ((userRole.getName().substring(app.getAuthNamespace().length() + 1)) + .equals(role.getName())) { + newUpdatedRoles.add(userRole); + } + } + } + if (newUpdatedRoles.size() > 0) { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles); + } else { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); + currentUserRolesToUpdate = new HashMap<>(); + + } + + } else { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); + currentUserRolesToUpdate = new HashMap<>(); + + } + } + + // Check if user roles does not exists in local but still there in External Central Auth System delete them all + for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) { + if (!(currentUserRolesToUpdate + .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) { + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}", + userRole.getName()); + 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.getName(), deleteResponse.getBody()); + } + } + // Check if user roles does not exists in External Central Auth System add them all + for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) { + if (!(currentUserRolesInExternalSystem + .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_")))) { + ExternalAccessUser extUser = new ExternalAccessUser(name, + app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_")); + String formattedUserRole = mapper.writeValueAsString(extUser); + HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}", + name, addUserRole.getRoleName()); + ResponseEntity<String> addResponse = template + .exchange(SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole", HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}", + addResponse.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", + addResponse.getBody(), + addUserRole.getRoleName()); + throw new Exception(addResponse.getBody()); + } + } + } + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", + app.getId(), e); + if (e.getStatusCode() == HttpStatus.FORBIDDEN) { + logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", + orgUserId); + throw new HttpClientErrorException(HttpStatus.FORBIDDEN, + "Please enter the valid systemUser"); + } + if (e.getStatusCode() == HttpStatus.NOT_FOUND) { + logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role"); + throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role"); + } + EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST); + throw e; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", + app.getId(), e); + EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST); + throw e; } - } - transaction.commit(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - EcompPortalUtils.rollbackTransaction(transaction, - "Exception occurred in syncUserRoles, Details: " + e.toString()); - if ("DELETE".equals(reqType)) { - throw new SyncUserRolesException(e.getMessage()); - } } - } - - private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) { - HashMap<Long, EcompRole> result = new HashMap<>(); - if (ecompRoles != null) { - for (EcompRole ecompRole : ecompRoles) { - if (ecompRole.getId() != null) { - result.put(ecompRole.getId(), ecompRole); + + private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList( + List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) { + Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app); + //Add Account Admin role for partner app to prevent conflict + if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) { + FnRole role = new FnRole(); + role.setRoleName(PortalConstants.ADMIN_ROLE + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + epRoleList.put(role.getRoleName(), role); } - } + userRoleDetailList.removeIf( + userRoleDetail -> !epRoleList + .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1))); + return userRoleDetailList; } - return result; - } - private void syncUserRolesExtension(FnUserRole userRole, Long appId, - HashMap<Long, EcompRole> newUserAppRolesMap) { + private List<FnUser> checkIfUserExists(String userParams) { + return fnUserService.getUserWithOrgUserId(userParams); + } + + @Transactional + private void createLocalUserIfNecessary(String userId, boolean isSystemUser) { + if (StringUtils.isEmpty(userId)) { + logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!"); + return; + } + try { + List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId); + if (userList.size() == 0) { + FnUser client; + if (!isSystemUser) { + client = fnUserService.loadUserByUsername(userId); + } else { + client = new FnUser(); + client.setOrgUserId(userId); + client.setIsSystemUser(true); + client.setFirstName(userId.substring(0, userId.indexOf("@"))); + } + if (client == null) { + String msg = "createLocalUserIfNecessary: cannot create user " + userId + + ", because not found in phonebook"; + logger.error(EELFLoggerDelegate.errorLogger, msg); + } else { + client.setLoginId(userId); + client.setActiveYn(true); + } + fnUserService.saveFnUser(client); + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + } - Long userAppRoleId; - if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app - userAppRoleId = userRole.getRoleId().getId(); - } else { // remote app - userAppRoleId = userRole.getId(); } - if (!newUserAppRolesMap.containsKey(userAppRoleId)) { - fnUserRoleService.deleteById(userRole.getId()); - } else { - newUserAppRolesMap.remove(userAppRoleId); + private FnUser checkIfRemoteUserExits(String userId, FnApp app, + ApplicationsRestClientService applicationsRestClientService) throws HTTPException { + FnUser checkRemoteUser = null; + try { + checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService); + } catch (HTTPException e) { + // Some apps are returning 400 if user is not found. + if (e.getResponseCode() == 400) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", + e); + } else if (e.getResponseCode() == 404) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing", + e); + } else { + // Other response code, let it come thru. + throw e; + } + } + return checkRemoteUser; } - } - - private Role fnRoleToRole(final FnRole role) { - return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null, role.getActiveYn(), - role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles()); - } - - @SuppressWarnings("unchecked") - public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue, Long userId) { - List<RoleInAppForUser> rolesInAppForUser = null; - FnApp app = fnAppService.getById(appId); - logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app); - try { - // for onap portal app, no need to make a remote call - List<Role> roleList = new ArrayList<>(); - if (!PortalConstants.PORTAL_APP_ID.equals(appId)) { - if (app.getAuthCentral()) { - List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey()); - for (CentralV2Role cenRole : cenRoleList) { - Role role = new Role(); - role.setActiveYn(cenRole.isActive()); - role.setId(cenRole.getId()); - role.setRoleName(cenRole.getName()); - role.setPriority(cenRole.getPriority()); - roleList.add(role); - } - } else { - Optional<FnUser> user = fnUserService.getUser(userId); - if (user.isPresent()) { - roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole).collect(Collectors.toList()); - } + + private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService) + throws HTTPException { + if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) { + List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId); + if (userList != null && !userList.isEmpty()) { + return userList.get(0); + } else { + return null; + } } - List<Role> activeRoleList = new ArrayList<>(); - for (Role role : roleList) { - if (role.getActiveYn()) { - if (role.getId() != 1) { // prevent portal admin from being added - activeRoleList.add(role); - } else if (extRequestValue) { - activeRoleList.add(role); + return getUser(userId, app, applicationsRestClientService); + } + + private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, + boolean externalSystemRequest, String reqType, boolean isSystemUser, + Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception { + boolean result = false; + String userId = rolesInAppForUser.getOrgUserId(); + Long appId = rolesInAppForUser.getAppId(); + synchronized (syncRests) { + createLocalUserIfNecessary(userId, isSystemUser); + + EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()]; + for (int i = 0; + i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) { + RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i); + EcompRole role = new EcompRole(); + role.setId(roleInAppForUser.getRoleId()); + role.setName(roleInAppForUser.getRoleName()); + userAppRoles[i] = role; } - } + try { + EcompRole[] applicationRoles = null; + + if (isLoggedInUserRoleAdminOfApp) { + List<EcompRole> roles = Arrays.stream(userAppRoles) + .collect(Collectors.toList()); + List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover); + roles.addAll(roles1); + applicationRoles = roles.toArray(new EcompRole[0]); + } + syncUserRoles(userId, appId, userAppRoles, externalSystemRequest, + reqType, isLoggedInUserRoleAdminOfApp, applicationRoles); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + + userId, e); + if ("DELETE".equals(reqType)) { + throw new Exception(e.getMessage()); + } + } } - FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService); - // If localUser does not exists return roles - Set<FnRole> roleSet = null; - FnRole[] roleSetList = null; - if (localUser != null) { - roleSet = localUser.getAppEPRoles(app); - roleSetList = roleSet.toArray(new FnRole[0]); + return result; + } + + private void syncUserRoles(String userId, Long appId, + EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin, + EcompRole[] appRoles) throws Exception { + + Transaction transaction = null; + String roleActive; + HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles); + List<FnRole> roleInfo = externalAccessRolesService + .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); + FnRole adminRole = new FnRole(); + if (roleInfo.size() > 0) { + adminRole = roleInfo.get(0); + logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName()); } - rolesInAppForUser = fnUserRoleService - .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue); - return rolesInAppForUser; - } - - EcompRole[] appRoles = null; - boolean checkIfUserIsApplicationAccAdmin = false; - List<EcompRole> roles = new ArrayList<>(); - if (app.getAuthCentral()) { - List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId()); - FnApp application = fnAppService.getById(appId); - checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId, - application); - - List<FnRole> roleSetWithFunctioncds = new ArrayList<>(); - for (FnRole role : applicationRoles) { - List<EpAppFunction> cenRoleFuncList = epAppFunctionService.getAppRoleFunctionList(role.getId(), app.getId()); - for (EpAppFunction roleFunc : cenRoleFuncList) { - - String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd()); - functionCode = EPUserUtils.decodeFunctionCode(functionCode); - String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd()); - String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd()); - String name = roleFunc.getFunctionName(); - - FnFunction function = new FnFunction(); - function.setAction(action); - function.setType(type); - function.setCode(functionCode); - function.setName(name); - role.getFnRoleFunctions().add(new FnRoleFunction(role, function)); - - } - roleSetWithFunctioncds.add(role); + try { + List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId); + if (userList.size() > 0) { + FnUser client = userList.get(0); + roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'"; + List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId); + entityManager + .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive) + .setParameter("appId", appId) + .setParameter("userId", client.getId()) + .getResultList(); + + if ("DELETE".equals(reqType)) { + for (FnUserRole userAppRoleList : userRoles) { + List<FnRole> rolesList = + (!userAppRoleList.getRoleId().getRoleName() + .equals(adminRole.getRoleName())) + ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId + (userAppRoleList.getRoleId().getRoleName(), appId) + : fnRoleService.retrieveAppRolesWhereAppIdIsNull(); + if (!rolesList.isEmpty()) { + checkIfRoleInactive(rolesList.get(0)); + } + } + } + if (appRoles != null) { + List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList()); + List<FnUserRole> finalUserRolesList = new ArrayList<>(); + if (checkIfUserisRoleAdmin) { + for (EcompRole role : appRolesList) { + for (FnUserRole userAppRoleList : userRoles) { + if (userAppRoleList.getRoleId().getRoleName() + .equals(role.getName())) { + finalUserRolesList.add(userAppRoleList); + } + + } + } + userRoles = new ArrayList<>(finalUserRolesList); + } + } - } + for (FnUserRole userRole : userRoles) { + if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId()) + && !PortalConstants.SYS_ADMIN_ROLE_ID + .equals(userRole.getRoleId().getId()) + && !extRequestValue) { + syncUserRolesExtension(userRole, appId, + newUserAppRolesMap); + } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) + || "DELETE".equals(reqType))) { + syncUserRolesExtension(userRole, appId, + newUserAppRolesMap); + } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID + .equals(userRole.getRoleId().getId())) { + syncUserRolesExtension(userRole, appId, + newUserAppRolesMap); + } + } - for (FnRole role1 : roleSetWithFunctioncds) { - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(role1.getId()); - ecompRole.setName(role1.getRoleName()); - ecompRole.setRoleFunctions(role1.getRoleFunctions()); - roles.add(ecompRole); + Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values(); + if (newRolesToAdd.size() > 0) { + FnApp app = fnAppService.getById(appId); + + HashMap<Long, FnRole> rolesMap = new HashMap<>(); + if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app + String appIdValue = ""; + if (!extRequestValue) { + appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID; + } + @SuppressWarnings("unchecked") + List<FnRole> roles = entityManager + .createQuery( + "from " + FnRole.class.getName() + " where appId is null " + + appIdValue).getResultList(); + for (FnRole role : roles) { + role.setAppId(1L); + rolesMap.put(role.getId(), role); + } + } else { // remote app + @SuppressWarnings("unchecked") + List<FnRole> roles = entityManager + .createQuery("from EPRole where appId=:appId") + .setParameter("appId", appId) + .getResultList(); + for (FnRole role : roles) { + if (!extRequestValue && app.getAuthCentral()) { + rolesMap.put(role.getId(), role); + } else { + rolesMap.put(role.getAppRoleId(), role); + } + } + } - } - if (checkIfUserIsApplicationAccAdmin) { - appRoles = roles.toArray(new EcompRole[roles.size()]); - logger.debug(EELFLoggerDelegate.debugLogger, - "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles); - } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) { - List<EcompRole> roleAdminAppRoles = new ArrayList<>(); - List<String> roleAdminAppRolesNames = new ArrayList<>(); - String QUERY = - "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr" - + " where fu.role_id = ep.role_id" - + " and fu.app_id = ep.app_id" - + " and fu.user_id = :userId" - + " and fu.role_id = fr.role_id and fr.active_yn='Y'" - + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'" - + " and exists" - + " (" - + " select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id" - + " and ur.app_id = fa.app_id and fa.enabled = 'Y')"; - List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class) - .setParameter("userId", userId) - .getResultList(); - List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName")) - .collect(Collectors.toList()); - - List<EcompRole> userapproverRolesList = new ArrayList<>(); - for (String str : getUserApproverRoles) { - EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null); - if (epRole != null) { - userapproverRolesList.add(epRole); + FnRole role; + for (EcompRole userRole : newRolesToAdd) { + FnUserRole userApp = new FnUserRole(); + if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName() + .equals(adminRole.getRoleName())) { + role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); + userApp.setRoleId(role); + } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) + && !extRequestValue) { + continue; + } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app + .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) { + continue; + } else { + userApp.setRoleId(rolesMap.get(userRole.getId())); + } + + userApp.setUserId(client); + userApp.setFnAppId(app); + fnUserRoleService.saveOne(userApp); + } + + if (PortalConstants.PORTAL_APP_ID.equals(appId)) { + /* + * for local app -- hack - always make sure fn_role + * table's app_id is null and not 1 for primary app in + * this case being onap portal app; reason: hibernate + * is rightly setting this to 1 while persisting to + * fn_role as per the mapping but SDK role management + * code expects the app_id to be null as there is no + * concept of App_id in SDK + */ + Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 "); + query.executeUpdate(); + } + } + } + transaction.commit(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncUserRoles, Details: " + e.toString()); + if ("DELETE".equals(reqType)) { + throw new SyncUserRolesException(e.getMessage()); } - } - for (EcompRole role : userapproverRolesList) { - - List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions()); - boolean checkIfFunctionsExits = roleFunList.stream() - .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver")); - if (checkIfFunctionsExits) { - roleAdminAppRoles.add(role); - List<RoleFunction> filteredList = roleFunList.stream() - .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList()); - roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode) - .collect(Collectors.toList())); + } + } + + private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) { + HashMap<Long, EcompRole> result = new HashMap<>(); + if (ecompRoles != null) { + for (EcompRole ecompRole : ecompRoles) { + if (ecompRole.getId() != null) { + result.put(ecompRole.getId(), ecompRole); + } } - } - for (String name : roleAdminAppRolesNames) { - roles.stream().filter(x -> name.equals(x.getName())).findAny().ifPresent(roleAdminAppRoles::add); + } + return result; + } - } - appRoles = roleAdminAppRoles.toArray(new EcompRole[0]); + private void syncUserRolesExtension(FnUserRole userRole, Long appId, + HashMap<Long, EcompRole> newUserAppRolesMap) { + Long userAppRoleId; + if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app + userAppRoleId = userRole.getRoleId().getId(); + } else { // remote app + userAppRoleId = userRole.getId(); } - } else { - appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); - } - // Test this error case, for generating an internal ONAP Portal - // error - // EcompRole[] appRoles = null; - // If there is an exception in the rest client api, then null will - // be returned. - if (appRoles != null) { - if (!app.getAuthCentral()) { - syncAppRoles(appId, appRoles); + + if (!newUserAppRolesMap.containsKey(userAppRoleId)) { + fnUserRoleService.deleteById(userRole.getId()); + } else { + newUserAppRolesMap.remove(userAppRoleId); } - EcompRole[] userAppRoles = null; + } + + private Role fnRoleToRole(final FnRole role) { + return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null, + role.getActiveYn(), + role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles()); + } + + @SuppressWarnings("unchecked") + public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue, + Long userId) { + List<RoleInAppForUser> rolesInAppForUser = null; + FnApp app = fnAppService.getById(appId); + logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app); try { - try { - if (app.getAuthCentral()) { - List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId)); - List<EPUserAppCurrentRoles> userAppsRolesList = entityManager - .createNamedQuery("EPUserAppCurrentRoles") - .setParameter("appId", app.getId()) - .setParameter("userId", actualUser.get(0).getId()) - .getResultList(); - List<EcompRole> setUserRoles = new ArrayList<>(); - for (EPUserAppCurrentRoles role : userAppsRolesList) { - logger.debug(EELFLoggerDelegate.debugLogger, - "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName()); - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(role.getRoleId()); - ecompRole.setName(role.getRoleName()); - setUserRoles.add(ecompRole); - } - - boolean checkIfUserisAccAdmin = setUserRoles.stream() - .anyMatch(ecompRole -> ecompRole.getId() == 999L); - - if (!checkIfUserisAccAdmin) { - List<EcompRole> appRolesList = Arrays.asList(appRoles); - Set<EcompRole> finalUserAppRolesList = new HashSet<>(); - - List<String> roleNames = new ArrayList<>(); - for (EcompRole role : setUserRoles) { - EcompRole epRole = appRolesList.stream() - .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null); - List<RoleFunction> roleFunList = new ArrayList<>(); - - if (epRole != null) { - if (epRole.getRoleFunctions().size() > 0) { - roleFunList.addAll(epRole.getRoleFunctions()); + // for onap portal app, no need to make a remote call + List<Role> roleList = new ArrayList<>(); + if (!PortalConstants.PORTAL_APP_ID.equals(appId)) { + if (app.getAuthCentral()) { + List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey()); + for (CentralV2Role cenRole : cenRoleList) { + Role role = new Role(); + role.setActiveYn(cenRole.isActive()); + role.setId(cenRole.getId()); + role.setRoleName(cenRole.getName()); + role.setPriority(cenRole.getPriority()); + roleList.add(role); } - boolean checkIfFunctionsExits = roleFunList.stream().anyMatch( - roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver")); - if (checkIfFunctionsExits) { - finalUserAppRolesList.add(role); - List<RoleFunction> filteredList = roleFunList.stream() - .filter(x -> "Approver".equalsIgnoreCase(x.getType())) - .collect(Collectors.toList()); - roleNames = filteredList.stream().map(RoleFunction::getCode) - .collect(Collectors.toList()); - } else { - roleNames.add(epRole.getName()); + } else { + Optional<FnUser> user = fnUserService.getUser(userId); + if (user.isPresent()) { + roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole) + .collect(Collectors.toList()); } - } - for (String name : roleNames) { - EcompRole ecompRole = appRolesList.stream() - .filter(x -> name.equals(x.getName())).findAny().orElse(null); - if (ecompRole != null) { - finalUserAppRolesList.add(ecompRole); + } + List<Role> activeRoleList = new ArrayList<>(); + for (Role role : roleList) { + if (role.getActiveYn()) { + if (role.getId() != 1) { // prevent portal admin from being added + activeRoleList.add(role); + } else if (extRequestValue) { + activeRoleList.add(role); + } } - } + } - for (String name : roleNames) { - boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch( - role -> role.getRoleName().equalsIgnoreCase(name)); - if (checkIfFunctionsExits) { - appRolesList.stream().filter(x -> name.equals(x.getName())) - .findAny().ifPresent(setUserRoles::add); - } + FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService); + // If localUser does not exists return roles + Set<FnRole> roleSet = null; + FnRole[] roleSetList = null; + if (localUser != null) { + roleSet = localUser.getAppEPRoles(app); + roleSetList = roleSet.toArray(new FnRole[0]); } - userAppRoles = setUserRoles.toArray(new EcompRole[0]); - } - } else { - userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, - String.format("/user/%s/roles", userId)); + rolesInAppForUser = fnUserRoleService + .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue); + return rolesInAppForUser; } - } catch (HTTPException e) { - // Some apps are returning 400 if user is not found. - if (e.getResponseCode() == 400) { - logger.debug(EELFLoggerDelegate.debugLogger, - "getAppRolesForUser caught exception with response code 400; continuing", e); + + EcompRole[] appRoles = null; + boolean checkIfUserIsApplicationAccAdmin = false; + List<EcompRole> roles = new ArrayList<>(); + if (app.getAuthCentral()) { + List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId()); + FnApp application = fnAppService.getById(appId); + checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId, + application); + + List<FnRole> roleSetWithFunctioncds = new ArrayList<>(); + for (FnRole role : applicationRoles) { + List<EpAppFunction> cenRoleFuncList = epAppFunctionService + .getAppRoleFunctionList(role.getId(), app.getId()); + for (EpAppFunction roleFunc : cenRoleFuncList) { + + String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd()); + functionCode = EPUserUtils.decodeFunctionCode(functionCode); + String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd()); + String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd()); + String name = roleFunc.getFunctionName(); + + FnFunction function = new FnFunction(); + function.setAction(action); + function.setType(type); + function.setCode(functionCode); + function.setName(name); + role.getFnRoleFunctions().add(new FnRoleFunction(role, function)); + + } + roleSetWithFunctioncds.add(role); + + + } + + for (FnRole role1 : roleSetWithFunctioncds) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(role1.getId()); + ecompRole.setName(role1.getRoleName()); + ecompRole.setRoleFunctions(role1.getRoleFunctions()); + roles.add(ecompRole); + + } + if (checkIfUserIsApplicationAccAdmin) { + appRoles = roles.toArray(new EcompRole[roles.size()]); + logger.debug(EELFLoggerDelegate.debugLogger, + "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", + appRoles); + } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) { + List<EcompRole> roleAdminAppRoles = new ArrayList<>(); + List<String> roleAdminAppRolesNames = new ArrayList<>(); + String QUERY = + "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr" + + " where fu.role_id = ep.role_id" + + " and fu.app_id = ep.app_id" + + " and fu.user_id = :userId" + + " and fu.role_id = fr.role_id and fr.active_yn='Y'" + + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'" + + " and exists" + + " (" + + " select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id" + + " and ur.app_id = fa.app_id and fa.enabled = 'Y')"; + List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class) + .setParameter("userId", userId) + .getResultList(); + List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName")) + .collect(Collectors.toList()); + + List<EcompRole> userapproverRolesList = new ArrayList<>(); + for (String str : getUserApproverRoles) { + EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null); + if (epRole != null) { + userapproverRolesList.add(epRole); + } + } + for (EcompRole role : userapproverRolesList) { + + List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions()); + boolean checkIfFunctionsExits = roleFunList.stream() + .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver")); + if (checkIfFunctionsExits) { + roleAdminAppRoles.add(role); + List<RoleFunction> filteredList = roleFunList.stream() + .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList()); + roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode) + .collect(Collectors.toList())); + } + } + for (String name : roleAdminAppRolesNames) { + roles.stream().filter(x -> name.equals(x.getName())).findAny() + .ifPresent(roleAdminAppRoles::add); + + } + appRoles = roleAdminAppRoles.toArray(new EcompRole[0]); + + } } else { - // Other response code, let it come thru. - throw e; - } - } - if (userAppRoles == null) { - if (EcompPortalUtils.getExternalAppResponseCode() == 400) { - EcompPortalUtils.setExternalAppResponseCode(200); - String message = String.format( - "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, " - + "assuming user doesn't exist, app is framework SDK based, and things are ok. " - + "Overriding to 200 until framework SDK returns a useful response.", - Long.toString(appId), userId); - logger.warn(EELFLoggerDelegate.applicationLogger, message); + appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); } - } + // Test this error case, for generating an internal ONAP Portal + // error + // EcompRole[] appRoles = null; + // If there is an exception in the rest client api, then null will + // be returned. + if (appRoles != null) { + if (!app.getAuthCentral()) { + syncAppRoles(appId, appRoles); + } + EcompRole[] userAppRoles = null; + try { + try { + if (app.getAuthCentral()) { + List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId)); + List<EPUserAppCurrentRoles> userAppsRolesList = entityManager + .createNamedQuery("EPUserAppCurrentRoles") + .setParameter("appId", app.getId()) + .setParameter("userId", actualUser.get(0).getId()) + .getResultList(); + List<EcompRole> setUserRoles = new ArrayList<>(); + for (EPUserAppCurrentRoles role : userAppsRolesList) { + logger.debug(EELFLoggerDelegate.debugLogger, + "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", + role.getRoleName()); + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(role.getRoleId()); + ecompRole.setName(role.getRoleName()); + setUserRoles.add(ecompRole); + } + + boolean checkIfUserisAccAdmin = setUserRoles.stream() + .anyMatch(ecompRole -> ecompRole.getId() == 999L); + + if (!checkIfUserisAccAdmin) { + List<EcompRole> appRolesList = Arrays.asList(appRoles); + Set<EcompRole> finalUserAppRolesList = new HashSet<>(); + + List<String> roleNames = new ArrayList<>(); + for (EcompRole role : setUserRoles) { + EcompRole epRole = appRolesList.stream() + .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null); + List<RoleFunction> roleFunList = new ArrayList<>(); + + if (epRole != null) { + if (epRole.getRoleFunctions().size() > 0) { + roleFunList.addAll(epRole.getRoleFunctions()); + } + boolean checkIfFunctionsExits = roleFunList.stream().anyMatch( + roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver")); + if (checkIfFunctionsExits) { + finalUserAppRolesList.add(role); + List<RoleFunction> filteredList = roleFunList.stream() + .filter(x -> "Approver".equalsIgnoreCase(x.getType())) + .collect(Collectors.toList()); + roleNames = filteredList.stream().map(RoleFunction::getCode) + .collect(Collectors.toList()); + } else { + roleNames.add(epRole.getName()); + } + } + for (String name : roleNames) { + EcompRole ecompRole = appRolesList.stream() + .filter(x -> name.equals(x.getName())).findAny().orElse(null); + if (ecompRole != null) { + finalUserAppRolesList.add(ecompRole); + } + } + } + for (String name : roleNames) { + boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch( + role -> role.getRoleName().equalsIgnoreCase(name)); + if (checkIfFunctionsExits) { + appRolesList.stream().filter(x -> name.equals(x.getName())) + .findAny().ifPresent(setUserRoles::add); + } + } + userAppRoles = setUserRoles.toArray(new EcompRole[0]); + } + } else { + userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", userId)); + } + } catch (HTTPException e) { + // Some apps are returning 400 if user is not found. + if (e.getResponseCode() == 400) { + logger.debug(EELFLoggerDelegate.debugLogger, + "getAppRolesForUser caught exception with response code 400; continuing", e); + } else { + // Other response code, let it come thru. + throw e; + } + } + if (userAppRoles == null) { + if (EcompPortalUtils.getExternalAppResponseCode() == 400) { + EcompPortalUtils.setExternalAppResponseCode(200); + String message = String.format( + "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, " + + "assuming user doesn't exist, app is framework SDK based, and things are ok. " + + "Overriding to 200 until framework SDK returns a useful response.", + Long.toString(appId), userId); + logger.warn(EELFLoggerDelegate.applicationLogger, message); + } + } - HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles); - ArrayList<EcompRole> activeRoles = new ArrayList<>(); - if (userAppRoles != null) { - for (EcompRole userAppRole : userAppRoles) { - if (appRolesActiveMap.containsKey(userAppRole.getId())) { - EcompRole role = new EcompRole(); - role.setId(userAppRole.getId()); - role.setName(userAppRole.getName()); - activeRoles.add(role); - } - } - } - EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]); + HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles); + ArrayList<EcompRole> activeRoles = new ArrayList<>(); + if (userAppRoles != null) { + for (EcompRole userAppRole : userAppRoles) { + if (appRolesActiveMap.containsKey(userAppRole.getId())) { + EcompRole role = new EcompRole(); + role.setId(userAppRole.getId()); + role.setName(userAppRole.getName()); + activeRoles.add(role); + } + } + } + EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]); - boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin; + boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin; - // If the remote application isn't down we MUST sync user - // roles here in case we have this user here! - syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null, checkIfUserisRoleAdmin, - appRoles); + // If the remote application isn't down we MUST sync user + // roles here in case we have this user here! + syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null, + checkIfUserisRoleAdmin, + appRoles); + } catch (Exception e) { + // TODO: we may need to check if user exists, maybe remote + // app is down. + String message = String.format( + "getAppRolesForUser: user %s does not exist in remote application %s", userId, + Long.toString(appId)); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + userAppRoles = new EcompRole[0]; + } + rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles); + } } catch (Exception e) { - // TODO: we may need to check if user exists, maybe remote - // app is down. - String message = String.format( - "getAppRolesForUser: user %s does not exist in remote application %s", userId, - Long.toString(appId)); - logger.error(EELFLoggerDelegate.errorLogger, message, e); - userAppRoles = new EcompRole[0]; + String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId, + Long.toString(appId)); + logger.error(EELFLoggerDelegate.errorLogger, message, e); } - rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles); - } - } catch (Exception e) { - String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId, - Long.toString(appId)); - logger.error(EELFLoggerDelegate.errorLogger, message, e); + return rolesInAppForUser; } - return rolesInAppForUser; - } - - private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception { - logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId); - HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles); - try { - List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId); - - List<FnRole> obsoleteRoles = new ArrayList<>(); - for (FnRole oldAppRole : currentAppRoles) { - if (oldAppRole.getAppRoleId() != null) { - EcompRole role; - role = newRolesMap.get(oldAppRole.getAppRoleId()); - if (role != null) { - if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) { - oldAppRole.setRoleName(role.getName()); + + private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId); + HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles); + try { + List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId); + + List<FnRole> obsoleteRoles = new ArrayList<>(); + for (FnRole oldAppRole : currentAppRoles) { + if (oldAppRole.getAppRoleId() != null) { + EcompRole role; + role = newRolesMap.get(oldAppRole.getAppRoleId()); + if (role != null) { + if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) { + oldAppRole.setRoleName(role.getName()); + } + oldAppRole.setActiveYn(true); + newRolesMap.remove(oldAppRole.getAppRoleId()); + } else { + obsoleteRoles.add(oldAppRole); + } + } else { + obsoleteRoles.add(oldAppRole); + } } - oldAppRole.setActiveYn(true); - newRolesMap.remove(oldAppRole.getAppRoleId()); - } else { - obsoleteRoles.add(oldAppRole); - } - } else { - obsoleteRoles.add(oldAppRole); - } - } - Collection<EcompRole> newRolesToAdd = newRolesMap.values(); - if (obsoleteRoles.size() > 0) { - logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete"); - for (FnRole role : obsoleteRoles) { - logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString()); - Long roleId = role.getId(); - List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId); - - logger.debug(EELFLoggerDelegate.debugLogger, - "syncAppRoles: number of userRoles to delete: " + userRoles.size()); - for (FnUserRole userRole : userRoles) { - logger.debug(EELFLoggerDelegate.debugLogger, - "syncAppRoles: about to delete userRole: " + userRole.toString()); - fnUserRoleService.deleteById(userRole.getId()); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncAppRoles: finished deleting userRole: " + userRole.toString()); - } - List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId); - int numMenuRoles = funcMenuRoles.size(); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); - for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) { - Long menuId = funcMenuRole.getMenuId().getMenuId(); - // 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 - List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService.retrieveByMenuId(menuId); - int numMenuRoles2 = funcMenuRoles2.size(); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); - fnMenuFunctionalRolesService.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, - "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url"); - List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId); - if (funcMenuItems.size() > 0) { - logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); - FnMenuFunctional funcMenuItem = funcMenuItems.get(0); - funcMenuItem.setUrl(""); - } + Collection<EcompRole> newRolesToAdd = newRolesMap.values(); + if (obsoleteRoles.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete"); + for (FnRole role : obsoleteRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString()); + Long roleId = role.getId(); + List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId); + + logger.debug(EELFLoggerDelegate.debugLogger, + "syncAppRoles: number of userRoles to delete: " + userRoles.size()); + for (FnUserRole userRole : userRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, + "syncAppRoles: about to delete userRole: " + userRole.toString()); + fnUserRoleService.deleteById(userRole.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncAppRoles: finished deleting userRole: " + userRole.toString()); + } + List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId); + int numMenuRoles = funcMenuRoles.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); + for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) { + Long menuId = funcMenuRole.getMenuId().getMenuId(); + // 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 + List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService + .retrieveByMenuId(menuId); + int numMenuRoles2 = funcMenuRoles2.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); + fnMenuFunctionalRolesService.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, + "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url"); + List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId); + if (funcMenuItems.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); + FnMenuFunctional funcMenuItem = funcMenuItems.get(0); + funcMenuItem.setUrl(""); + } + } + } + boolean isPortalRequest = true; + deleteRoleDependencyRecords(roleId, appId, isPortalRequest); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncAppRoles: about to delete the role: " + role.toString()); + fnRoleService.delete(role); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role"); + } + } + for (EcompRole role : newRolesToAdd) { + logger.debug(EELFLoggerDelegate.debugLogger, + "syncAppRoles: about to add missing role: " + role.toString()); + FnRole newRole = new FnRole(); + // Attention! All roles from remote application supposed to be + // active! + newRole.setActiveYn(true); + newRole.setRoleName(role.getName()); + newRole.setAppId(appId); + newRole.setAppRoleId(role.getId()); + fnRoleService.saveOne(newRole); } - } - boolean isPortalRequest = true; - deleteRoleDependencyRecords(roleId, appId, isPortalRequest); - logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString()); - fnRoleService.delete(role); - logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role"); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction"); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + throw new Exception(e); } - } - for (EcompRole role : newRolesToAdd) { - logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString()); - FnRole newRole = new FnRole(); - // Attention! All roles from remote application supposed to be - // active! - newRole.setActiveYn(true); - newRole.setRoleName(role.getName()); - newRole.setAppId(appId); - newRole.setAppRoleId(role.getId()); - fnRoleService.saveOne(newRole); - } - logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction"); - logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - throw new Exception(e); - } - } - - private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest) - throws Exception { - Session localSession = entityManager.unwrap(Session.class); - try { - String sql; - Query query; - // It should delete only when it portal's roleId - if (appId.equals(PortalConstants.PORTAL_APP_ID)) { - // Delete from fn_role_function - sql = "DELETE FROM fn_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; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - } - // 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 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 - 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 - 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(); - if (!isPortalRequest) { - // 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 DeleteDomainObjectFailedException("delete Failed" + e.getMessage()); } - } - private void checkIfRoleInactive(FnRole epRole) throws Exception { - if (!epRole.getActiveYn()) { - throw new Exception(epRole.getRoleName() + " role is unavailable"); - } - } - - public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) { - boolean result = false; - // No changes if no new roles list or no userId. - if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId()) - && newAppsListWithAdminRoles.getAppsRoles() != null) { - synchronized (syncRests) { - List<FnApp> apps = fnAppService.getAppsFullList(); - HashMap<Long, FnApp> enabledApps = new HashMap<>(); - for (FnApp app : apps) { - enabledApps.put(app.getId(), app); - } - List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>(); - for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) { - // user Admin role may be added only for enabled apps - if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) { - newAppsWhereUserIsAdmin.add(adminRole); - } - } - FnUser user = null; - boolean createNewUser = false; - String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim(); - List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId); - List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>(); - if (localUserList.size() > 0) { - FnUser tmpUser = localUserList.get(0); - oldAppsWhereUserIsAdmin = fnUserRoleService.retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID); - if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) { - user = tmpUser; - } - } else if (newAppsWhereUserIsAdmin.size() > 0) { - // we create new user only if he has Admin Role for any App - createNewUser = true; + private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest) + throws Exception { + Session localSession = entityManager.unwrap(Session.class); + try { + String sql; + Query query; + // It should delete only when it portal's roleId + if (appId.equals(PortalConstants.PORTAL_APP_ID)) { + // Delete from fn_role_function + sql = "DELETE FROM fn_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; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + } + // 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 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 + 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 + 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(); + if (!isPortalRequest) { + // 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 DeleteDomainObjectFailedException("delete Failed" + e.getMessage()); } - result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId, - oldAppsWhereUserIsAdmin); - } } - return result; - } - - @Transactional - public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps, - List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId, - List<FnUserRole> oldAppsWhereUserIsAdmin) { - if (user != null || createNewUser) { - if (createNewUser) { - user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get(); - if (user != null) { - user.setActiveYn(true); - } - } - for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) { - // user Admin role may be deleted only for enabled - // apps - if (enabledApps.containsKey(oldUserApp.getFnAppId())) { - fnUserRoleService.saveOne(oldUserApp); + private void checkIfRoleInactive(FnRole epRole) throws Exception { + if (!epRole.getActiveYn()) { + throw new Exception(epRole.getRoleName() + " role is unavailable"); } - } - for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) { - FnApp app = fnAppService.getById(appNameIdIsAdmin.getId()); - FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID); - FnUserRole newUserApp = new FnUserRole(); - newUserApp.setUserId(user); - newUserApp.setFnAppId(app); - newUserApp.setRoleId(role); - fnUserRoleService.saveOne(newUserApp); - } - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin); - result = true; - } } - return result; - } - - @Transactional() - public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) { - boolean result = false; - try { - // Reset All admin role for centralized applications - List<FnApp> appList = fnAppService.getCentralizedApps(); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - for (FnApp app : appList) { - String name = ""; - if (EPCommonSystemProperties - .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { - name = user.getOrgUserId() + SystemProperties - .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + + public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) { + boolean result = false; + // No changes if no new roles list or no userId. + if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId()) + && newAppsListWithAdminRoles.getAppsRoles() != null) { + synchronized (syncRests) { + List<FnApp> apps = fnAppService.getAppsFullList(); + HashMap<Long, FnApp> enabledApps = new HashMap<>(); + for (FnApp app : apps) { + enabledApps.put(app.getId(), app); + } + List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>(); + for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) { + // user Admin role may be added only for enabled apps + if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) { + newAppsWhereUserIsAdmin.add(adminRole); + } + } + FnUser user = null; + boolean createNewUser = false; + String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim(); + List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId); + List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>(); + if (localUserList.size() > 0) { + FnUser tmpUser = localUserList.get(0); + oldAppsWhereUserIsAdmin = fnUserRoleService + .retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID); + if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) { + user = tmpUser; + } + } else if (newAppsWhereUserIsAdmin.size() > 0) { + // we create new user only if he has Admin Role for any App + createNewUser = true; + } + result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId, + oldAppsWhereUserIsAdmin); + } } - String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - try { - ResponseEntity<String> getResponse = template - .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "roles/" + extRole, HttpMethod.GET, entity, String.class); - - if (getResponse.getBody().equals("{}")) { - String addDesc = "{\"name\":\"" + extRole + "\"}"; - HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role", - HttpMethod.POST, roleEntity, String.class); - } else { - try { - HttpEntity<String> deleteUserRole = new HttpEntity<>(headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "userRole/" + name + "/" + extRole, - HttpMethod.DELETE, deleteUserRole, String.class); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - " Role not found for this user may be it gets deleted before", e); + + return result; + } + + @Transactional + public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps, + List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId, + List<FnUserRole> oldAppsWhereUserIsAdmin) { + if (user != null || createNewUser) { + if (createNewUser) { + user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get(); + if (user != null) { + user.setActiveYn(true); + } + } + for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) { + // user Admin role may be deleted only for enabled + // apps + if (enabledApps.containsKey(oldUserApp.getFnAppId())) { + fnUserRoleService.saveOne(oldUserApp); + } + } + for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) { + FnApp app = fnAppService.getById(appNameIdIsAdmin.getId()); + FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID); + FnUserRole newUserApp = new FnUserRole(); + newUserApp.setUserId(user); + newUserApp.setFnAppId(app); + newUserApp.setRoleId(role); + fnUserRoleService.saveOne(newUserApp); + } + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin); + result = true; } - } - } catch (Exception e) { - if (e.getMessage().equalsIgnoreCase("404 Not Found")) { - logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}", - app.getAuthNamespace(), e.getMessage()); - } else { - logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}", - app.getAuthNamespace(), e); - } } - } - for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) { - FnApp app = fnAppService.getById(appNameIdIsAdmin.getId()); + return result; + } + + public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) { + boolean result = false; try { - if (app.getAuthCentral()) { - String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); - HttpEntity<String> entity = new HttpEntity<>(headers); - String name = ""; - if (EPCommonSystemProperties - .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { - name = user.getOrgUserId() + SystemProperties - .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); - } - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); - ResponseEntity<String> getUserRolesResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "userRoles/user/" + name, - HttpMethod.GET, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); - if (!getUserRolesResponse.getBody().equals("{}")) { - JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody()); - JSONArray extRoles = jsonObj.getJSONArray("userRole"); - final Map<String, JSONObject> extUserRoles = new HashMap<>(); - for (int i = 0; i < extRoles.length(); i++) { - String userRole = extRoles.getJSONObject(i).getString("role"); - if (userRole.startsWith(app.getAuthNamespace() + ".") - && !userRole.equals(app.getAuthNamespace() + ".admin") - && !userRole.equals(app.getAuthNamespace() + ".owner")) { - - extUserRoles.put(userRole, extRoles.getJSONObject(i)); + // Reset All admin role for centralized applications + List<FnApp> appList = fnAppService.getCentralizedApps(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (FnApp app : appList) { + String name = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = user.getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); } - } - if (!extUserRoles.containsKey(extRole)) { - // Assign with new apps user admin + String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); try { - ExternalAccessUser extUser = new ExternalAccessUser(name, extRole); - // Assign user role for an application in external access system - ObjectMapper addUserRoleMapper = new ObjectMapper(); - String userRole = addUserRoleMapper.writeValueAsString(extUser); - HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers); - template.exchange( - SystemProperties.getProperty( - EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", - HttpMethod.POST, addUserRole, String.class); + ResponseEntity<String> getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/" + extRole, HttpMethod.GET, entity, String.class); + + if (getResponse.getBody().equals("{}")) { + String addDesc = "{\"name\":\"" + extRole + "\"}"; + HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role", + HttpMethod.POST, roleEntity, String.class); + } else { + try { + HttpEntity<String> deleteUserRole = new HttpEntity<>(headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + extRole, + HttpMethod.DELETE, deleteUserRole, String.class); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " Role not found for this user may be it gets deleted before", e); + } + } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e); + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}", + app.getAuthNamespace(), e.getMessage()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}", + app.getAuthNamespace(), e); + } + } + } + for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) { + FnApp app = fnAppService.getById(appNameIdIsAdmin.getId()); + try { + if (app.getAuthCentral()) { + String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); + HttpEntity<String> entity = new HttpEntity<>(headers); + String name = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = user.getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> getUserRolesResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRoles/user/" + name, + HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + if (!getUserRolesResponse.getBody().equals("{}")) { + JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody()); + JSONArray extRoles = jsonObj.getJSONArray("userRole"); + final Map<String, JSONObject> extUserRoles = new HashMap<>(); + for (int i = 0; i < extRoles.length(); i++) { + String userRole = extRoles.getJSONObject(i).getString("role"); + if (userRole.startsWith(app.getAuthNamespace() + ".") + && !userRole.equals(app.getAuthNamespace() + ".admin") + && !userRole.equals(app.getAuthNamespace() + ".owner")) { + + extUserRoles.put(userRole, extRoles.getJSONObject(i)); + } + } + if (!extUserRoles.containsKey(extRole)) { + // Assign with new apps user admin + try { + ExternalAccessUser extUser = new ExternalAccessUser(name, extRole); + // Assign user role for an application in external access system + ObjectMapper addUserRoleMapper = new ObjectMapper(); + String userRole = addUserRoleMapper.writeValueAsString(extUser); + HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, addUserRole, String.class); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e); + } + + } + } + } + result = true; + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.errorLogger, + "Application name space not found in External system for app {} due to bad rquest name space ", + app.getAuthNamespace(), e.getMessage()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}", + app.getAuthNamespace(), e); + result = false; + } } - - } } - } - result = true; } catch (Exception e) { - if (e.getMessage().equalsIgnoreCase("404 Not Found")) { - logger.debug(EELFLoggerDelegate.errorLogger, - "Application name space not found in External system for app {} due to bad rquest name space ", - app.getAuthNamespace(), e.getMessage()); - } else { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}", - app.getAuthNamespace(), e); result = false; - } + logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e); + } + return result; + } + + public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException { + final String getAllAppsFunctionsOfUser = + "select distinct ep.function_cd from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_app fa , fn_role fr\n" + + " where fu.role_id = ep.role_id \n" + + " and fu.app_id = ep.app_id\n" + + " and fu.user_id =:userId\n" + + " and ea.function_cd = ep.function_cd\n" + + " and ((fu.app_id = fa.app_id and fa.enabled = 'Y' ) or (fa.app_id = 1))\n" + + " and fr.role_id = fu.role_id and fr.active_yn='Y' \n" + + " union\n" + + " select distinct app_r_f.function_cd from ep_app_role_function app_r_f, ep_app_function a_f\n" + + " where role_id = 999\n" + + " and app_r_f.function_cd = a_f.function_cd\n" + + " and exists\n" + + " (\n" + + " select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id\n" + + " and ur.role_id = 999 and ur.app_id = fa.app_id and fa.enabled = 'Y'\n" + + " )"; + List getRoleFuncListOfPortal = entityManager.createNativeQuery(getAllAppsFunctionsOfUser) + .setParameter("userId", OrgUserId).getResultList(); + Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal); + Set<String> roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")) + .collect(Collectors.toSet()); + if (!roleFunSet.isEmpty()) { + for (String roleFunction : roleFunSet) { + String roleFun = EcompPortalUtils.getFunctionCode(roleFunction); + getRoleFuncListOfPortalSet.remove(roleFunction); + getRoleFuncListOfPortalSet.add(roleFun); + } } - } - } catch (Exception e) { - result = false; - logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e); + + Set<String> finalRoleFunctionSet = new HashSet<>(); + for (String roleFn : getRoleFuncListOfPortalSet) { + finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn)); + } + + return finalRoleFunctionSet; } - return result; - } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/EcompAppRoleService.java b/portal-BE/src/main/java/org/onap/portal/service/EcompAppRoleService.java new file mode 100644 index 00000000..41291757 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/EcompAppRoleService.java @@ -0,0 +1,73 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.service; + +import java.util.List; +import javax.persistence.EntityManager; +import javax.transaction.Transactional; +import org.onap.portal.domain.dto.ecomp.EcompAppRole; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +@Transactional +public class EcompAppRoleService { + + private final String notificationAppRoles = + "select a.app_id, a.app_name, b.role_id, b.role_name from\n" + + "(select * from fn_app where app_id = 1) a,\n" + + "(select * from fn_role where app_id is null and active_yn = 'Y' and role_id <> 1) b\n" + + "union\n" + + "select fn_role.app_id,fn_app.app_name, fn_role.role_id ,fn_role.role_name\n" + + "from fn_app, fn_role\n" + + "where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_yn='Y' order by app_name"; + + private final EntityManager entityManager; + + @Autowired + public EcompAppRoleService(EntityManager entityManager) { + this.entityManager = entityManager; + } + + public List<EcompAppRole> getAppRoleList() { + return entityManager.createQuery(notificationAppRoles, EcompAppRole.class).getResultList(); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/EpNotificationItemVOService.java b/portal-BE/src/main/java/org/onap/portal/service/EpNotificationItemVOService.java new file mode 100644 index 00000000..6a282e81 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/EpNotificationItemVOService.java @@ -0,0 +1,186 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.service; + +import java.util.List; +import javax.persistence.EntityManager; +import javax.transaction.Transactional; +import org.onap.portal.domain.dto.transport.EpNotificationItemVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +@Transactional +public class EpNotificationItemVOService { + + private final EntityManager entityManager; + + private final String notificationHistoryVOResult = + "\t\tSELECT\n" + + "\t\t\tnotificationId, isForOnlineUsers, isForAllRoles, msgHeader,\tmsgDescription,msgSource,\n" + + "\t\t\tstartTime, endTime, priority, createdDate,notificationHyperlink,creatorId, loginId,\tactiveYn \n" + + "\t\tFROM\n" + + "\t\t\t(\n" + + "\t\t\t\t\tselect distinct \n" + + "\t\t\t\t\ta.notification_ID AS notificationId, \n" + + "\t\t\t\t\tis_for_online_users AS isForOnlineUsers, \n" + + "\t\t\t\t\tis_for_all_roles AS isForAllRoles, \n" + + "\t\t\t\t\tmsg_header AS msgHeader, \n" + + "\t\t\t\t\tmsg_description AS msgDescription,\n" + + "\t\t\t\t\tmsg_source AS msgSource, \n" + + "\t\t\t\t\tstart_Time AS startTime, \n" + + "\t\t\t\t\tend_time AS endTime, \n" + + "\t\t\t\t\tpriority,\n" + + "\t\t\t\t\tcreated_date AS createdDate, \n" + + "\t\t\t\t\tcreator_ID AS creatorId,\n" + + "\t\t\t\t\tnotification_hyperlink AS notificationHyperlink,\n" + + "\t\t\t\t\tlogin_id AS loginId,\n" + + "\t\t\t\t\tactive_YN AS activeYn, \n" + + "\t\t\t\t\tif (is_viewed is null, 'N', is_viewed)\n" + + "\t\t\tfrom\n" + + "\t\t\t(\n" + + "\t\t\t\tselect \n" + + "\t\t\t\t\tuser_id, login_id,notification_id, is_for_online_users, is_for_all_roles, \n" + + "\t\t\t\t\tmsg_header, msg_description,msg_source, start_Time, end_time, priority, created_date, \n" + + "\t\t\t\t\tcreator_ID,notification_hyperlink,active_YN\n" + + "\t\t\t\tfrom\n" + + "\t\t\t\t(\n" + + "\t\t\t\t\tselect a.notification_ID,a.is_for_online_users,a.is_for_all_roles,a.active_YN,\n" + + "\t\t\t\t\ta.msg_header,a.msg_description,a.msg_source,a.start_time,a.end_time,a.priority,a.creator_ID,a.notification_hyperlink,a.created_date, \n" + + "\t\t\t\t\t b.role_id,CASE WHEN a.creator_ID IS NOT NULL THEN u.org_user_id\n" + + " \n" + + " ELSE NULL\n" + + " END AS login_id,b.recv_user_id \n" + + "\t\t\t\tfrom ep_notification a, ep_role_notification b,fn_user u\n" + + "\t\t\t\twhere a.notification_id = b.notification_id and (u.user_id=a.creator_ID OR a.creator_ID IS NULL)\n" + + "\t\t\t\tand a.is_for_all_roles = 'N'\n" + + "\t\t\t\tand (\n" + + "\t\t\t\t(start_time is null and end_time is null and a.created_date >= DATE_ADD(curdate(),INTERVAL-31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is not null and end_time is null and start_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is null and end_time is not null and end_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is not null and end_time is not null and end_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\t)\n" + + "\t\t\t\t) a,\n" + + "\t\t\t\t(\n" + + "\t\t\t\tselect distinct a.user_id, c.role_id, c.app_id, d.APP_NAME\n" + + "\t\t\t\tfrom fn_user a, fn_user_role b, fn_role c, fn_app d\n" + + "\t\t\t\twhere COALESCE(c.app_id,1) = d.app_id\n" + + " \t\tand a.user_id = b.user_id\n" + + "\t\t\t\tand a.user_id = :user_id\n" + + "\t\t\t\tand b.role_id = c.role_id\n" + + " \t\t\tand (d.enabled='Y' or d.app_id=1)\n" + + "\t\t\t\t) b\n" + + "\t\t\t\twhere\n" + + "\t\t\t\t(\n" + + "\t\t\t\ta.role_id = b.role_id\n" + + "\t\t\t\t)\n" + + "\t\t\t\t UNION\n" + + " \t\tselect \n" + + "\t\t\t\t\t:user_id, login_id,notification_id, is_for_online_users, is_for_all_roles, \n" + + "\t\t\t\t\tmsg_header, msg_description,msg_source, start_Time, end_time, priority, created_date, \n" + + "\t\t\t\t\tcreator_ID,notification_hyperlink,active_YN\n" + + "\t\t\t\tfrom\n" + + "\t\t\t\t(\n" + + "\t\t\t\t\tselect a.notification_ID,a.is_for_online_users,a.is_for_all_roles,a.active_YN,\n" + + "\t\t\t\t\ta.msg_header,a.msg_description,a.msg_source,a.start_time,a.end_time,a.priority,a.creator_ID,a.created_date,a.notification_hyperlink, \n" + + "\t\t\t\t\t b.role_id,CASE WHEN a.creator_ID IS NOT NULL THEN u.org_user_id\n" + + " \n" + + " ELSE NULL\n" + + " END AS login_id,b.recv_user_id \n" + + "\t\t\t\tfrom ep_notification a, ep_role_notification b,fn_user u\n" + + "\t\t\t\twhere a.notification_id = b.notification_id and (u.user_id=a.creator_ID OR a.creator_ID IS NULL)\n" + + "\t\t\t\tand a.is_for_all_roles = 'N'\n" + + "\t\t\t\tand (\n" + + "\t\t\t\t(start_time is null and end_time is null and a.created_date >= DATE_ADD(curdate(),INTERVAL-31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is not null and end_time is null and start_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is null and end_time is not null and end_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is not null and end_time is not null and end_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\t)\n" + + "\t\t\t\t) a\n" + + "\t\t where\n" + + "\t\t (\n" + + "\t\t a.recv_user_id=:user_id\n" + + "\t\t )\n" + + "\t\t\t\tunion\n" + + "\t\t\t\t(\n" + + "\t\t\t\tselect \n" + + "\t\t\t\t\t:user_id user_id, b.login_id,notification_id, is_for_online_users, is_for_all_roles,\n" + + "\t\t\t\t\tmsg_header, msg_description,msg_source, start_Time, end_time, priority, a.created_date, \n" + + "\t\t\t\t\tcreator_ID, a.notification_hyperlink,a.active_YN\n" + + "\t\t\t\tfrom ep_notification a JOIN fn_user b on b.user_id=a.creator_ID\n" + + "\t\t\t\twhere a.notification_id\n" + + "\t\t\t\tand a.is_for_all_roles = 'Y'\n" + + "\t\t\t\tand (\n" + + "\t\t\t\t(start_time is null and end_time is null and a.created_date >= DATE_ADD(curdate(),INTERVAL-31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is not null and end_time is null and start_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is null and end_time is not null and end_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\tor\n" + + "\t\t\t\t(start_time is not null and end_time is not null and end_time >= DATE_ADD(curdate(),INTERVAL -31 DAY))\n" + + "\t\t\t\t)\n" + + "\t\t\t\t)\n" + + "\t\t\t\t) a left outer join (\n" + + "\t\t\t\tselect m.notification_ID, m.is_viewed from ep_user_notification m where user_id = :user_id\n" + + "\t\t\t\t) m\n" + + "\t\t\t\ton a.notification_id = m.notification_ID\n" + + "\t\t\t\twhere\n" + + "\t\t\t\tactive_YN = 'Y'\n" + + "\t\t\t\t\n" + + "\t\t\t\torder by start_Time desc,end_time desc\n" + + "\t\t\t) t,\n" + + " (SELECT @rn /*'*/:=/*'*/ 0) t2 where startTime<=SYSDATE() "; + + @Autowired + public EpNotificationItemVOService(EntityManager entityManager) { + this.entityManager = entityManager; + } + + public List<EpNotificationItemVO> getNotificationHistoryVO(Long id) { + return entityManager.createQuery(notificationHistoryVOResult, EpNotificationItemVO.class).setParameter("user_id", id).getResultList(); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java b/portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java index 2a5d0aec..afaccfd2 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java @@ -45,65 +45,69 @@ import java.util.List; import java.util.stream.Collectors; import org.onap.portal.domain.db.ep.EpPersUserWidgetSel; import org.onap.portal.domain.db.ep.EpWidgetCatalog; -import org.onap.portal.domain.db.fn.FnUser; import org.onap.portal.domain.dto.ecomp.PersUserWidgetSelection; import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization; import org.onap.portal.service.persUserWidgetSel.EpPersUserWidgetSelService; +import org.onap.portal.service.user.FnUserService; import org.onap.portal.service.widgetCatalog.EpWidgetCatalogService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional +@EnableAspectJAutoProxy public class PersUserWidgetService { private static final Logger LOGGER = LoggerFactory.getLogger(PersUserWidgetService.class); private final EpPersUserWidgetSelService epPersUserWidgetSelService; private final EpWidgetCatalogService epWidgetCatalogService; + private final FnUserService fnUserService; @Autowired public PersUserWidgetService(final EpPersUserWidgetSelService epPersUserWidgetSelService, - final EpWidgetCatalogService epWidgetCatalogService) { + final EpWidgetCatalogService epWidgetCatalogService, + FnUserService fnUserService) { this.epPersUserWidgetSelService = epPersUserWidgetSelService; this.epWidgetCatalogService = epWidgetCatalogService; + this.fnUserService = fnUserService; } - public void setPersUserAppValue(FnUser user, WidgetCatalogPersonalization personalization) { - List<PersUserWidgetSelection> persList = getUserWidgetSelction(user, personalization.getWidgetId()); + public void setPersUserAppValue(final long userId, final WidgetCatalogPersonalization personalization) { + List<PersUserWidgetSelection> persList = getUserWidgetSelction(userId, personalization.getWidgetId()); LOGGER.info("Error: " + persList.size()); // Key constraint limits to 1 row PersUserWidgetSelection persRow; if (persList.size() == 1) { persRow = persList.get(0); } else { - persRow = new PersUserWidgetSelection(null, user.getId(), personalization.getWidgetId(), null); + persRow = new PersUserWidgetSelection(null, userId, personalization.getWidgetId(), null); } - if (persRow.getId() != null) { epPersUserWidgetSelService.deleteById(persRow.getId()); } - persRow.setStatusCode(personalization.getSelect() ? "S" : "H"); // Show / Hide EpPersUserWidgetSel epPersUserWidgetSel = new EpPersUserWidgetSel(); - epPersUserWidgetSel.setUserId(user); - epPersUserWidgetSel.setWidgetId( - epWidgetCatalogService.findById(personalization.getWidgetId()).orElse(new EpWidgetCatalog())); + epPersUserWidgetSel.setUserId(fnUserService.getUser(userId).get()); + EpWidgetCatalog catalog = epWidgetCatalogService.findById(personalization.getWidgetId()).orElse(new EpWidgetCatalog()); + epWidgetCatalogService.save(catalog); + epPersUserWidgetSel.setWidgetId(catalog); epPersUserWidgetSelService.saveAndFlush(epPersUserWidgetSel); } - private List<PersUserWidgetSelection> getUserWidgetSelction(FnUser user, Long widgetId) { + private List<PersUserWidgetSelection> getUserWidgetSelction(final long userId, final long widgetId) { return epPersUserWidgetSelService - .getEpPersUserWidgetSelForUserIdAndWidgetId(user.getId(), widgetId) + .getEpPersUserWidgetSelForUserIdAndWidgetId(userId, widgetId) .orElse(new ArrayList<>()) .stream() .map(this::epPersUserWidgetSelToPersUserWidgetSelection) .collect(Collectors.toList()); } - private PersUserWidgetSelection epPersUserWidgetSelToPersUserWidgetSelection(EpPersUserWidgetSel widgetSel) { + private PersUserWidgetSelection epPersUserWidgetSelToPersUserWidgetSelection(final EpPersUserWidgetSel widgetSel) { return new PersUserWidgetSelection(widgetSel.getId(), widgetSel.getUserId().getId(), widgetSel.getWidgetId().getWidgetId(), widgetSel.getStatusCd()); } diff --git a/portal-BE/src/main/java/org/onap/portal/service/epNotification/EpNotificationDao.java b/portal-BE/src/main/java/org/onap/portal/service/epNotification/EpNotificationDao.java new file mode 100644 index 00000000..57ea5a09 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/epNotification/EpNotificationDao.java @@ -0,0 +1,57 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.service.epNotification; + +import java.util.List; +import org.onap.portal.domain.db.ep.EpNotification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +@Repository +interface EpNotificationDao extends JpaRepository<EpNotification, Long> { + + @Query + List<EpNotification> getNotifications(@Param("user_id") final Long userId); +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/epNotification/EpNotificationService.java b/portal-BE/src/main/java/org/onap/portal/service/epNotification/EpNotificationService.java new file mode 100644 index 00000000..e4a5c025 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/epNotification/EpNotificationService.java @@ -0,0 +1,139 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.service.epNotification; + +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import javax.persistence.EntityManager; +import javax.transaction.Transactional; +import org.hibernate.transform.Transformers; +import org.onap.portal.domain.db.ep.EpNotification; +import org.onap.portal.domain.db.ep.EpRoleNotification; +import org.onap.portal.domain.db.fn.FnRole; +import org.onap.portal.domain.dto.transport.EpNotificationItemVO; +import org.onap.portal.service.role.FnRoleService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +@Transactional +public class EpNotificationService { + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(EpNotificationService.class); + + + private final EpNotificationDao epNotificationDao; + private final FnRoleService fnRoleService; + private final EntityManager entityManager; + + private final String messageRecipients = "select u.org_user_id from ep_notification n join ep_role_notification r on " + + " r.notification_ID=n.notification_ID join fn_user u on u.user_id=r.recv_user_id where n.notification_id=:notificationId\n"; + + @Autowired + public EpNotificationService( + final EpNotificationDao epNotificationDao, + FnRoleService fnRoleService, final EntityManager entityManager) { + this.epNotificationDao = epNotificationDao; + this.fnRoleService = fnRoleService; + this.entityManager = entityManager; + } + + public Optional<EpNotification> getOne(final long notficationId){ + return Optional.of(epNotificationDao.getOne(notficationId)); + } + + public List<EpNotification> getNotifications(final Long userId) { + List<EpNotification> notificationList = epNotificationDao.getNotifications(userId); + for (EpNotification item : notificationList) { + item.setEpRoleNotifications(null); + } + return notificationList; + } + + public List<EpNotificationItemVO> getAdminNotificationVOS(final Long userId) { + return entityManager.createNamedQuery("getAdminNotificationHistoryVO") + .setParameter("user_id", userId).unwrap(org.hibernate.query.NativeQuery.class) + .setResultTransformer(Transformers.aliasToBean( EpNotificationItemVO.class )) + .getResultList(); + } + + + public EpNotification saveNotification(final EpNotification notificationItem) { + + // gather the roles + if (notificationItem.getRoleIds() != null && !notificationItem.getIsForAllRoles().equals("Y")) { + if (notificationItem.getEpRoleNotifications() == null) { + Set<EpRoleNotification> roleSet = new HashSet<>(); + notificationItem.setEpRoleNotifications(roleSet); + } + for (Long roleId : notificationItem.getRoleIds()) { + FnRole role = null; + try { + role = fnRoleService.getById(roleId); + EpRoleNotification roleItem = new EpRoleNotification(); + roleItem.setNotificationId(notificationItem); + roleItem.setRoleId(role); + notificationItem.getEpRoleNotifications().add(roleItem); + }catch (Exception e){ + LOGGER.error(e.getMessage()); + } + } + } + + // for updates fetch roles and then save + if (notificationItem.getNotificationId() != null) { + Optional<EpNotification> updateNotificationItem = Optional.of(epNotificationDao.getOne(notificationItem.getNotificationId())); + updateNotificationItem.ifPresent( + epNotification -> notificationItem.setEpRoleNotifications(epNotification.getEpRoleNotifications())); + } + if (notificationItem.getMsgSource() == null) { + notificationItem.setMsgSource("EP"); + } + return epNotificationDao.saveAndFlush(notificationItem); + } + + public List<String> getMessageRecipients(final Long notificationId) { + return entityManager.createQuery(messageRecipients, String.class).setParameter("notificationId", notificationId).getResultList(); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/epRoleNotification/EpRoleNotificationDao.java b/portal-BE/src/main/java/org/onap/portal/service/epRoleNotification/EpRoleNotificationDao.java new file mode 100644 index 00000000..b1dd19c9 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/epRoleNotification/EpRoleNotificationDao.java @@ -0,0 +1,58 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.service.epRoleNotification; + +import java.util.List; +import java.util.Optional; +import javax.transaction.Transactional; +import org.onap.portal.domain.db.ep.EpRoleNotification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +@Repository +@Transactional +interface EpRoleNotificationDao extends JpaRepository<EpRoleNotification, Long> { + + @Query + Optional<List<EpRoleNotification>> getNotificationRoles(@Param("notificationId") long notificationId); +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/epRoleNotification/EpRoleNotificationService.java b/portal-BE/src/main/java/org/onap/portal/service/epRoleNotification/EpRoleNotificationService.java new file mode 100644 index 00000000..9c467095 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/epRoleNotification/EpRoleNotificationService.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.service.epRoleNotification; + +import java.util.ArrayList; +import java.util.List; +import javax.transaction.Transactional; +import org.onap.portal.domain.db.ep.EpRoleNotification; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +@Transactional +public class EpRoleNotificationService { + + private final EpRoleNotificationDao epRoleNotificationDao; + + @Autowired + public EpRoleNotificationService( + EpRoleNotificationDao epRoleNotificationDao) { + this.epRoleNotificationDao = epRoleNotificationDao; + } + + public List<EpRoleNotification> getNotificationRoles(final Long notificationId) { + return epRoleNotificationDao.getNotificationRoles(notificationId).orElse(new ArrayList<>()); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/epUserNotification/EpUserNotificationDao.java b/portal-BE/src/main/java/org/onap/portal/service/epUserNotification/EpUserNotificationDao.java new file mode 100644 index 00000000..c59988d0 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/epUserNotification/EpUserNotificationDao.java @@ -0,0 +1,52 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.service.epUserNotification; + +import org.onap.portal.domain.db.ep.EpUserNotification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +@Repository +interface EpUserNotificationDao extends JpaRepository<EpUserNotification, Long> { + +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/epUserNotification/EpUserNotificationService.java b/portal-BE/src/main/java/org/onap/portal/service/epUserNotification/EpUserNotificationService.java new file mode 100644 index 00000000..b2815438 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/epUserNotification/EpUserNotificationService.java @@ -0,0 +1,86 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.service.epUserNotification; + +import java.time.LocalDateTime; +import javax.persistence.EntityExistsException; +import javax.transaction.Transactional; +import org.onap.portal.domain.db.ep.EpNotification; +import org.onap.portal.domain.db.ep.EpUserNotification; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.service.epNotification.EpNotificationService; +import org.onap.portal.service.user.FnUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +@Transactional +public class EpUserNotificationService { + + private final EpUserNotificationDao epUserNotificationDao; + private final EpNotificationService epNotificationService; + private final FnUserService fnUserService; + + @Autowired + public EpUserNotificationService( + final EpUserNotificationDao epUserNotificationDao, + final EpNotificationService epNotificationService, + final FnUserService fnUserService) { + this.epUserNotificationDao = epUserNotificationDao; + this.epNotificationService = epNotificationService; + this.fnUserService = fnUserService; + } + + public void setNotificationRead(Long notificationId, long userId) { + + EpNotification notification = epNotificationService.getOne(notificationId).orElse(new EpNotification()); + FnUser user = fnUserService.getUser(userId).orElseThrow(EntityExistsException::new); + + EpUserNotification userNotification = new EpUserNotification(); + userNotification.setNotificationId(notification); + userNotification.setUpdatedTime(LocalDateTime.now()); + userNotification.setIsViewed(true); + userNotification.setUserId(user); + + epUserNotificationDao.saveAndFlush(userNotification); + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/language/FnLanguageService.java b/portal-BE/src/main/java/org/onap/portal/service/language/FnLanguageService.java index 9221810e..67161b79 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/language/FnLanguageService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/language/FnLanguageService.java @@ -43,15 +43,12 @@ package org.onap.portal.service.language; import java.security.Principal; import java.util.List; import java.util.Optional; - import org.onap.portal.domain.db.fn.FnLanguage; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -@EnableAspectJAutoProxy @Transactional public class FnLanguageService { private final FnLanguageDao fnLanguageDao; diff --git a/portal-BE/src/main/java/org/onap/portal/service/menuFunctionalRoles/FnMenuFunctionalRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/menuFunctionalRoles/FnMenuFunctionalRolesService.java index 3a2c62a5..92511dfb 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/menuFunctionalRoles/FnMenuFunctionalRolesService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/menuFunctionalRoles/FnMenuFunctionalRolesService.java @@ -76,4 +76,8 @@ public class FnMenuFunctionalRolesService { public List<FnMenuFunctionalRoles> saveAll(List<FnMenuFunctionalRoles> functionalRoles) { return fnMenuFunctionalRolesDao.saveAll(functionalRoles); } + + public List<FnMenuFunctionalRoles> findAll(){ + return fnMenuFunctionalRolesDao.findAll(); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/persUserWidgetSel/EpPersUserWidgetSelService.java b/portal-BE/src/main/java/org/onap/portal/service/persUserWidgetSel/EpPersUserWidgetSelService.java index cd940d1c..307ef282 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/persUserWidgetSel/EpPersUserWidgetSelService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/persUserWidgetSel/EpPersUserWidgetSelService.java @@ -2,6 +2,7 @@ package org.onap.portal.service.persUserWidgetSel; import org.onap.portal.domain.db.ep.EpPersUserWidgetSel; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -9,24 +10,25 @@ import java.util.List; import java.util.Optional; @Service +@EnableAspectJAutoProxy public class EpPersUserWidgetSelService { private final EpPersUserWidgetSelDao epPersUserWidgetSelDao; @Autowired - public EpPersUserWidgetSelService(EpPersUserWidgetSelDao epPersUserWidgetSelDao) { + public EpPersUserWidgetSelService(final EpPersUserWidgetSelDao epPersUserWidgetSelDao) { this.epPersUserWidgetSelDao = epPersUserWidgetSelDao; } - public void deleteById(Long id) { + public void deleteById(final long id) { epPersUserWidgetSelDao.deleteById(id); } - public EpPersUserWidgetSel saveAndFlush(EpPersUserWidgetSel epPersUserWidgetSel) { + public EpPersUserWidgetSel saveAndFlush(final EpPersUserWidgetSel epPersUserWidgetSel) { return epPersUserWidgetSelDao.saveAndFlush(epPersUserWidgetSel); } - public Optional<List<EpPersUserWidgetSel>> getEpPersUserWidgetSelForUserIdAndWidgetId(Long id, Long widgetId) { + public Optional<List<EpPersUserWidgetSel>> getEpPersUserWidgetSelForUserIdAndWidgetId(final long id, final long widgetId) { return epPersUserWidgetSelDao.getEpPersUserWidgetSelForUserIdAndWidgetId(id, widgetId); } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextDao.java b/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextDao.java index 8faac5b6..df251027 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextDao.java +++ b/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextDao.java @@ -40,8 +40,13 @@ package org.onap.portal.service.sharedContext; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; import org.onap.portal.domain.db.fn.FnSharedContext; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @@ -49,4 +54,11 @@ import org.springframework.transaction.annotation.Transactional; @Transactional interface FnSharedContextDao extends JpaRepository<FnSharedContext, Long> { + @Query + Optional<List<FnSharedContext>> getByContextId(@Param("contextId") final String contextId); + @Query + Optional<List<FnSharedContext>> getByContextIdAndCkey(@Param("contextId") final String contextId, @Param("ckey") final String ckey); + @Query + void deleteByCreated(@Param("created") final LocalDateTime created); + } diff --git a/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextService.java b/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextService.java index 7a427ae9..ee0be613 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextService.java @@ -1,22 +1,128 @@ +/*- + * ============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============================================ + * + * + */ package org.onap.portal.service.sharedContext; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; import org.onap.portal.domain.db.fn.FnSharedContext; +import org.onap.portal.logging.aop.EPMetricsLog; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; -import java.util.List; @Service +@Transactional +@EnableAspectJAutoProxy +@EPMetricsLog public class FnSharedContextService { - private final FnSharedContextDao fnSharedContextDao; + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnSharedContextService.class); + + private final FnSharedContextDao fnSharedContextDao; + + @Autowired + public FnSharedContextService(final FnSharedContextDao fnSharedContextDao) { + this.fnSharedContextDao = fnSharedContextDao; + } + + public List<FnSharedContext> getSharedContexts(String contextId) { + return fnSharedContextDao.getByContextId(contextId).orElse(new ArrayList<>()); + } + + public FnSharedContext getFnSharedContext(String contextId, String ckey) { + FnSharedContext context = null; + Optional<List<FnSharedContext>> contexts = fnSharedContextDao.getByContextIdAndCkey(contextId, ckey); + if (contexts.isPresent() && contexts.get().size() == 1) { + context = contexts.get().get(0); + } + return context; + } + + public FnSharedContext addFnSharedContext(String contextId, String key, String value) { + return this.save(new FnSharedContext(contextId, key, value)); + } + + + public FnSharedContext save(FnSharedContext context) { + return this.fnSharedContextDao.saveAndFlush(context); + } + + public List<FnSharedContext> saveAll(List<FnSharedContext> fnSharedContexts){ + return fnSharedContextDao.saveAll(fnSharedContexts); + } + + public void delete(FnSharedContext context) { + this.fnSharedContextDao.delete(context); + } + + public int deleteSharedContexts(String contextId) { + // Uses an inefficient method to avoid a where clause + // that could be used to mount a SQL injection attack. + List<FnSharedContext> contexts = getSharedContexts(contextId); + if (contexts == null) + return 0; + + logger.debug(EELFLoggerDelegate.debugLogger, "deleteFnSharedContexts: count is " + contexts.size()); + for (FnSharedContext sc : contexts) + this.delete(sc); + + return contexts.size(); + } - @Autowired - public FnSharedContextService(FnSharedContextDao fnSharedContextDao) { - this.fnSharedContextDao = fnSharedContextDao; - } + public void expireFnSharedContexts(int ageInSeconds) { + Date expiredDateTime = new Date(System.currentTimeMillis() - ageInSeconds * 1000); + logger.debug(EELFLoggerDelegate.debugLogger, + "expireFnSharedContexts: expire time is " + expiredDateTime.toString()); + this.fnSharedContextDao.deleteByCreated(convertToLocalDateTimeViaInstant(expiredDateTime)); + } - public List<FnSharedContext> saveAll(List<FnSharedContext> sharedContexts) { - return fnSharedContextDao.saveAll(sharedContexts); - } + private LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/user/FnUserService.java b/portal-BE/src/main/java/org/onap/portal/service/user/FnUserService.java index 975bd219..23732d69 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/user/FnUserService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/user/FnUserService.java @@ -43,22 +43,19 @@ package org.onap.portal.service.user; import java.util.ArrayList; import java.util.List; import java.util.Optional; - import org.onap.portal.domain.db.fn.FnUser; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -@EnableAspectJAutoProxy @Transactional public class FnUserService implements UserDetailsService { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserService.class); + private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserService.class); private final FnUserDao fnUserDao; @@ -67,10 +64,6 @@ public class FnUserService implements UserDetailsService { this.fnUserDao = fnUserDao; } - public FnUser saveFnUser(final FnUser fnUser) { - return fnUserDao.save(fnUser); - } - @Override public FnUser loadUserByUsername(final String username) throws UsernameNotFoundException { Optional<FnUser> fnUser = fnUserDao.findByLoginId(username); @@ -81,6 +74,10 @@ public class FnUserService implements UserDetailsService { } } + public FnUser saveFnUser(final FnUser fnUser) { + return fnUserDao.save(fnUser); + } + public Optional<FnUser> getUser(final Long id) { return Optional.of(fnUserDao.getOne(id)); } @@ -93,7 +90,6 @@ public class FnUserService implements UserDetailsService { return fnUserDao.getUsersByOrgIds(orgIds).orElse(new ArrayList<>()); } - public List<FnUser> getActiveUsers() { return fnUserDao.getActiveUsers().orElse(new ArrayList<>()); } @@ -110,15 +106,15 @@ public class FnUserService implements UserDetailsService { return fnUserDao.findAll(); } - public List<FnUser> saveAll(List<FnUser> fnUsers) { + public List<FnUser> saveAll(final List<FnUser> fnUsers) { return fnUserDao.saveAll(fnUsers); } - public FnUser save(FnUser user) { + public FnUser save(final FnUser user) { return fnUserDao.save(user); } - public void delete(FnUser user) { + public void delete(final FnUser user) { fnUserDao.delete(user); } -}
\ No newline at end of file +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/widget/WidgetService.java b/portal-BE/src/main/java/org/onap/portal/service/widget/WidgetService.java index 05917eb4..9f515d2c 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/widget/WidgetService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/widget/WidgetService.java @@ -42,6 +42,7 @@ package org.onap.portal.service.widget; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import javax.persistence.EntityManager; import javax.servlet.http.HttpServletResponse; @@ -51,6 +52,7 @@ import org.onap.portal.domain.db.fn.FnWidget; import org.onap.portal.domain.dto.transport.FieldsValidator; import org.onap.portal.domain.dto.transport.OnboardingWidget; import org.onap.portal.service.AdminRolesService; +import org.onap.portal.service.user.FnUserService; import org.onap.portal.service.userRole.FnUserRoleService; import org.onap.portal.utils.EPCommonSystemProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -61,79 +63,105 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -@EnableAspectJAutoProxy @Transactional +@EnableAspectJAutoProxy public class WidgetService { - private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetService.class); - private final Long ACCOUNT_ADMIN_ROLE_ID = 999L; + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetService.class); + private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L; private static final String baseSqlToken = - " new org.onap.portal.domain.dto.transport.OnboardingWidget(" - + "widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID," - + "app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT," - + "widget.WDG_URL, widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,widget.WDG_URL) from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID"; + " new org.onap.portal.domain.dto.transport.OnboardingWidget(" + + "widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID," + + "app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT," + + "widget.WDG_URL, widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,widget.WDG_URL) from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID"; + + private static final String sqlWidgetsForAllApps = "SELECT" + baseSqlToken; + + private static final String sqlWidgetsForAllAppsWhereUserIsAdmin = + "SELECT" + baseSqlToken + + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = :USERID AND FN_USER_ROLE.ROLE_ID = " + + ACCOUNT_ADMIN_ROLE_ID; + + private static final String sqlWidgetsForAllAppsWhereUserHasAnyRole = + "SELECT DISTINCT" + baseSqlToken + + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + + ":USERID"; private static final String urlField = "url"; - private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long( - EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR); + private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = Long + .valueOf(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR); private static final String nameField = "name"; - private final AdminRolesService adminRolesService; private final EntityManager entityManager; private final FnWidgetDao fnWidgetDao; + private final FnUserService fnUserService; private final FnUserRoleService fnUserRoleService; + private static final Object syncRests = new Object(); + @Autowired public WidgetService(final AdminRolesService adminRolesService, final EntityManager entityManager, - final FnWidgetDao fnWidgetDao, FnUserRoleService fnUserRoleService) { + final FnWidgetDao fnWidgetDao, FnUserService fnUserService, + FnUserRoleService fnUserRoleService) { this.adminRolesService = adminRolesService; this.entityManager = entityManager; this.fnWidgetDao = fnWidgetDao; + this.fnUserService = fnUserService; this.fnUserRoleService = fnUserRoleService; } - private static final Object syncRests = new Object(); + @PreAuthorize("hasRole('System_Administrator')") + public FieldsValidator setOnboardingWidget(final Long userId, final OnboardingWidget onboardingWidget) { + return this.updateOrSaveWidget(true, userId, onboardingWidget); + } - public List<OnboardingWidget> getOnboardingWidgets(FnUser user, boolean managed) { - if (adminRolesService.isSuperAdmin(user.getOrgUserId())) { - return entityManager.createQuery(sqlWidgetsForAllApps(), OnboardingWidget.class).getResultList(); + public List<OnboardingWidget> getOnboardingWidgets(final String orgUserId, final long userId, final boolean managed) { + FnUser user = fnUserService.getUser(userId).get(); + if (adminRolesService.isSuperAdmin(orgUserId)){ + return entityManager.createQuery(sqlWidgetsForAllApps, OnboardingWidget.class).getResultList(); } else if (managed) { - if (adminRolesService.isAccountAdmin(user)) { + if (adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps())) { return entityManager - .createQuery(sqlWidgetsForAllAppsWhereUserIsAdmin(), OnboardingWidget.class) - .setParameter("USERID", user.getId()).getResultList(); + .createQuery(sqlWidgetsForAllAppsWhereUserIsAdmin, OnboardingWidget.class) + .setParameter("USERID", userId).getResultList(); } - } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) { + } else if (adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) || adminRolesService.isUser(userId)) { return entityManager - .createQuery(sqlWidgetsForAllAppsWhereUserHasAnyRole(), OnboardingWidget.class) - .setParameter("USERID", user.getId()).getResultList(); + .createQuery(sqlWidgetsForAllAppsWhereUserHasAnyRole, OnboardingWidget.class) + .setParameter("USERID", userId).getResultList(); } return new ArrayList<>(); } - private String sqlWidgetsForAllApps() { - return "SELECT" + baseSqlToken; - } - - private String sqlWidgetsForAllAppsWhereUserIsAdmin() { - return "SELECT" + baseSqlToken - + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = :USERID AND FN_USER_ROLE.ROLE_ID = " - + ACCOUNT_ADMIN_ROLE_ID; + public FnWidget saveOne(final FnWidget widget) { + return fnWidgetDao.saveAndFlush(widget); } - private String sqlWidgetsForAllAppsWhereUserHasAnyRole() { - return "SELECT DISTINCT" + baseSqlToken - + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " - + ":USERID"; + @PreAuthorize("hasRole('System_Administrator')") + public FieldsValidator deleteOnboardingWidget(final String orgUserId, final long userId, final long onboardingWidgetId) { + FieldsValidator fieldsValidator = new FieldsValidator(); + synchronized (syncRests) { + Optional<FnWidget> widget = this.getOne(onboardingWidgetId); + if (widget.isPresent() && widget.get().getAppId() != null) { // widget exists + if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(orgUserId), userId, + widget.get().getAppId())) { + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN); + } else { + fnWidgetDao.deleteById(onboardingWidgetId); + fieldsValidator.setHttpStatusCode( + (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + } + return fieldsValidator; } - @PreAuthorize("hasRole('System_Administrator')") - public FieldsValidator setOnboardingWidget(final Long userId, final OnboardingWidget onboardingWidget) { - return this.updateOrSaveWidget(true, userId, onboardingWidget); + public Optional<FnWidget> getOne(final long id) { + return Optional.of(fnWidgetDao.getOne(id)); } - private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) { + private FieldsValidator updateOrSaveWidget(final boolean superAdmin, final long userId, final OnboardingWidget onboardingWidget) { FieldsValidator fieldsValidator = new FieldsValidator(); if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.getAppId())) { fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN); @@ -143,8 +171,8 @@ public class WidgetService { if (onboardingWidget.getId() == null) { this.validateOnboardingWidget(onboardingWidget, fieldsValidator); } else { - FnWidget widget = fnWidgetDao.getOne(onboardingWidget.getId()); - if (widget == null || widget.getAppId() == null) { + Optional<FnWidget> widget = this.getOne(onboardingWidget.getId()); + if (!widget.isPresent() || widget.get().getAppId() == null) { fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_FOUND); return fieldsValidator; } @@ -157,19 +185,15 @@ public class WidgetService { return fieldsValidator; } - private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) { + private boolean isUserAdminOfAppForWidget(final boolean superAdmin, final Long userId, final Long appId) { if (!superAdmin) { - List<FnUserRole> userRoles = getAdminUserRoles(userId, appId); + List<FnUserRole> userRoles = fnUserRoleService.getAdminUserRoles(userId, ACCOUNT_ADMIN_ROLE_ID, appId); return (userRoles.size() > 0); } return true; } - private List<FnUserRole> getAdminUserRoles(Long userId, Long appId) { - return fnUserRoleService.getAdminUserRoles(userId, ACCOUNT_ADMIN_ROLE_ID, appId); - } - - private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) { + private void applyOnboardingWidget(final OnboardingWidget onboardingWidget, final FieldsValidator fieldsValidator) { boolean result; FnWidget widget; if (onboardingWidget.getId() == null) { @@ -188,34 +212,35 @@ public class WidgetService { } } - private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) { + private void validateOnboardingWidget(final OnboardingWidget onboardingWidget, + final FieldsValidator fieldsValidator) { List<FnWidget> widgets = getWidgets(onboardingWidget); - boolean dublicatedUrl = false; - boolean dublicatedName = false; + boolean duplicatedUrl = false; + boolean duplicatedName = false; for (FnWidget widget : widgets) { if (onboardingWidget.getId() != null && onboardingWidget.getId().equals(widget.getWidgetId())) { // widget should not be compared with itself continue; } - if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.getUrl())) { - dublicatedUrl = true; - if (dublicatedName) { + if (!duplicatedUrl && widget.getUrl().equals(onboardingWidget.getUrl())) { + duplicatedUrl = true; + if (duplicatedName) { break; } } - if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.getName()) && widget - .getAppId().equals(onboardingWidget.getAppId())) { - dublicatedName = true; - if (dublicatedUrl) { + if (!duplicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.getName()) && widget + .getAppId().equals(onboardingWidget.getAppId())) { + duplicatedName = true; + if (duplicatedUrl) { break; } } } - if (dublicatedUrl || dublicatedName) { - if (dublicatedUrl) { + if (duplicatedUrl || duplicatedName) { + if (duplicatedUrl) { fieldsValidator.addProblematicFieldName(urlField); } - if (dublicatedName) { + if (duplicatedName) { fieldsValidator.addProblematicFieldName(nameField); } fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_CONFLICT); @@ -224,28 +249,8 @@ public class WidgetService { } private List<FnWidget> getWidgets(final OnboardingWidget onboardingWidget) { - return fnWidgetDao.getForUrlNameAndAppId(onboardingWidget.getUrl(), onboardingWidget.getName(), onboardingWidget.getAppId()).orElse(new ArrayList<>()); - } - - public FieldsValidator deleteOnboardingWidget(FnUser user, Long onboardingWidgetId) { - FieldsValidator fieldsValidator = new FieldsValidator(); - synchronized (syncRests) { - FnWidget widget = fnWidgetDao.getOne(onboardingWidgetId); - if (widget != null && widget.getAppId() != null) { // widget exists - if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user.getOrgUserId()), user.getId(), - widget.getAppId())) { - fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN); - } else { - fnWidgetDao.deleteById(onboardingWidgetId); - fieldsValidator.setHttpStatusCode( - (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - } - return fieldsValidator; - } - - public FnWidget saveOne(final FnWidget widget){ - return fnWidgetDao.saveAndFlush(widget); + return fnWidgetDao + .getForUrlNameAndAppId(onboardingWidget.getUrl(), onboardingWidget.getName(), onboardingWidget.getAppId()) + .orElse(new ArrayList<>()); } } diff --git a/portal-BE/src/main/java/org/onap/portal/utils/DateUtil.java b/portal-BE/src/main/java/org/onap/portal/utils/DateUtil.java new file mode 100644 index 00000000..dc7164bc --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/utils/DateUtil.java @@ -0,0 +1,58 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * 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============================================ + * + * + */ + +package org.onap.portal.utils; + +import java.text.SimpleDateFormat; + +public class DateUtil { + + private DateUtil() { + throw new IllegalStateException("Utility class"); + } + + public static SimpleDateFormat getDateFormat() { + return new SimpleDateFormat("HH:mm:ss:SSSS"); + } + + public static SimpleDateFormat getRequestDateFormat(){ + return new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + } +} diff --git a/portal-BE/src/main/resources/conf/scheduler.properties b/portal-BE/src/main/resources/conf/scheduler.properties new file mode 100644 index 00000000..ce52554c --- /dev/null +++ b/portal-BE/src/main/resources/conf/scheduler.properties @@ -0,0 +1,61 @@ +### +# ============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============================================ +# +# +### + + +##scheduler authentication credentials +scheduler.user.name=test1 +scheduler.password=test2 +#scheduler properties +scheduler.server.url=http://mtanjv9sdlg10.aic.cip.onap.com:8989/scheduler +scheduler.create.new.vnf.change.instance=/v1/ChangeManagement/schedules/ +scheduler.get.time.slots=/v1/ChangeManagement/schedules/ +scheduler.submit.new.vnf.change=/v1/ChangeManagement/schedules/{scheduleId}/approvals +vid.truststore.filename=C:\\Temp\\vid_keystore.jks +vid.truststore.passwd.x=OBF:1wgg1wfq1uus1uui1x131x0r1x1v1x1j1uvo1uve1wg81wfi + +#scheduler-policy properties +policy.server.url=https://policypdp-conexus-e2e.ecomp.cci.onap.com:8081/pdp +policy.get.config=/api/getConfig +policy.ClientAuth=UHlQRFBTZXJ2ZXI6dGVzdA== +policy.client.mechId=m06814@controller.dcae.ecomp.onap.com +policy.client.password=OBF:1ffu1qvu1t2z1l161fuk1i801nz91ro41xf71xfv1rqi1nx51i7y1fuq1kxw1t371qxw1fh0 +policy.username=testpdp +policy.password=OBF:1igd1kft1l1a1sw61svs1kxs1kcl1idt +policy.Authorization=dGVzdHBkcDphbHBoYTEyMw== +policy.environment=TEST + diff --git a/portal-BE/src/test/java/org/onap/portal/service/PersUserWidgetServiceTest.java b/portal-BE/src/test/java/org/onap/portal/service/PersUserWidgetServiceTest.java new file mode 100644 index 00000000..35952053 --- /dev/null +++ b/portal-BE/src/test/java/org/onap/portal/service/PersUserWidgetServiceTest.java @@ -0,0 +1,48 @@ +package org.onap.portal.service; + +import static org.junit.jupiter.api.Assertions.*; + +import javax.transaction.Transactional; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +@Transactional +@TestPropertySource(locations = "classpath:test.properties") +class PersUserWidgetServiceTest { + + @Autowired + private PersUserWidgetService persUserWidgetService; + + @Test + void setPersUserAppValueInvalidWidgetIdDataTest() { + WidgetCatalogPersonalization catalog = getWidgetCatalog(); + catalog.setSelect(true); + try { + persUserWidgetService.setPersUserAppValue(1, catalog); + }catch (IllegalArgumentException e){ + assertEquals("widgetId may not be null", e.getMessage()); + } + } + + @Test + void setPersUserAppValueInvalidSelectDataTest() { + WidgetCatalogPersonalization catalog = getWidgetCatalog(); + catalog.setWidgetId(1L); + try { + persUserWidgetService.setPersUserAppValue(1, catalog); + }catch (IllegalArgumentException e){ + assertEquals("select may not be null", e.getMessage()); + } + } + + private WidgetCatalogPersonalization getWidgetCatalog(){ + return new WidgetCatalogPersonalization(); + } +} diff --git a/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java b/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java index 49c018e7..ef0a3e0b 100644 --- a/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java +++ b/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java @@ -141,7 +141,7 @@ class FnUserServiceTest { assertEquals(expected.getOrgUserId(), actual.getOrgUserId()); assertEquals(expected.getOrg_code(), actual.getOrg_code()); assertEquals(expected.getLoginId(), actual.getLoginId()); - assertEquals(expected.getLoginPwd(), actual.getLoginPwd()); + // assertEquals(expected.getLoginPwd(), actual.getLoginPwd()); assertEquals(expected.getActiveYn(), actual.getActiveYn()); assertEquals(expected.getIsInternalYn(), actual.getIsInternalYn()); assertEquals(expected.getAddressLine1(), actual.getAddressLine1()); @@ -178,4 +178,4 @@ class FnUserServiceTest { assertEquals(2, fnUserService.getUsersByOrgIds(ids).size()); } -}
\ No newline at end of file +} |