From 4694c152f69380f4d3d64bde0a13d15fb59a71f3 Mon Sep 17 00:00:00 2001 From: "a.sreekumar" Date: Fri, 3 Dec 2021 11:27:32 +0000 Subject: Migrate pap startup & controllers to spring boot This commit migrates pap config, startup and controllers to spring boot. Change-Id: Icf91d728160a23db614dfba6b40ddccd2f6163a5 Issue-ID: POLICY-3754 Signed-off-by: a.sreekumar --- main/pom.xml | 78 +++++-- .../onap/policy/pap/main/PapExceptionHandler.java | 85 ++++++++ .../onap/policy/pap/main/PolicyPapApplication.java | 42 ++++ .../policy/pap/main/comm/PdpMessageGenerator.java | 19 +- .../pap/main/comm/PdpStatusMessageHandler.java | 1 + .../onap/policy/pap/main/config/PapAafConfig.java | 42 ++++ .../policy/pap/main/config/WebSecurityConfig.java | 39 ++++ .../pap/main/parameters/PapParameterGroup.java | 18 +- .../pap/main/parameters/PapParameterHandler.java | 86 -------- .../policy/pap/main/parameters/PdpParameters.java | 3 + .../pap/main/parameters/PdpRequestParameters.java | 3 + .../policy/pap/main/rest/HealthCheckProvider.java | 3 + .../pap/main/rest/HealthCheckRestControllerV1.java | 24 ++- .../policy/pap/main/rest/PapRestControllerV1.java | 29 +-- .../rest/PdpGroupCreateOrUpdateControllerV1.java | 42 ++-- .../main/rest/PdpGroupCreateOrUpdateProvider.java | 10 +- .../pap/main/rest/PdpGroupDeleteControllerV1.java | 82 ++++---- .../pap/main/rest/PdpGroupDeleteProvider.java | 11 +- .../pap/main/rest/PdpGroupDeployControllerV1.java | 55 ++--- .../pap/main/rest/PdpGroupDeployProvider.java | 12 +- .../main/rest/PdpGroupHealthCheckControllerV1.java | 47 ++--- .../pap/main/rest/PdpGroupHealthCheckProvider.java | 9 +- .../pap/main/rest/PdpGroupQueryControllerV1.java | 46 ++--- .../pap/main/rest/PdpGroupQueryProvider.java | 9 +- .../main/rest/PdpGroupStateChangeControllerV1.java | 55 +++-- .../pap/main/rest/PdpGroupStateChangeProvider.java | 7 +- .../pap/main/rest/PolicyAuditControllerV1.java | 223 ++++++++++---------- .../policy/pap/main/rest/PolicyAuditProvider.java | 13 +- .../PolicyComponentsHealthCheckControllerV1.java | 44 ++-- .../rest/PolicyComponentsHealthCheckProvider.java | 56 ++--- .../pap/main/rest/PolicyStatusControllerV1.java | 181 +++++++++-------- .../policy/pap/main/rest/PolicyStatusProvider.java | 10 +- .../policy/pap/main/rest/PolicyUndeployerImpl.java | 4 +- .../onap/policy/pap/main/rest/ProviderBase.java | 15 +- .../pap/main/rest/StatisticsRestControllerV1.java | 225 ++++++++++----------- .../pap/main/rest/StatisticsRestProvider.java | 3 + .../org/onap/policy/pap/main/startstop/Main.java | 161 --------------- .../policy/pap/main/startstop/PapActivator.java | 81 ++++---- .../main/startstop/PapCommandLineArguments.java | 85 -------- .../pap/main/startstop/PapDatabaseInitializer.java | 26 ++- main/src/main/resources/application.yaml | 82 ++++++++ .../onap/policy/pap/main/comm/PublisherTest.java | 8 +- .../policy/pap/main/parameters/CommonTestData.java | 3 +- .../pap/main/parameters/TestPapParameterGroup.java | 19 +- .../main/parameters/TestPapParameterHandler.java | 145 ------------- .../policy/pap/main/rest/CommonPapRestServer.java | 138 ++++--------- .../pap/main/rest/PapRestControllerV1Test.java | 44 ++-- .../rest/TestPdpGroupCreateOrUpdateProvider.java | 2 + .../pap/main/rest/TestPdpGroupDeleteProvider.java | 9 +- .../pap/main/rest/TestPdpGroupDeployProvider.java | 2 + .../main/rest/TestPdpGroupHealthCheckProvider.java | 9 +- .../pap/main/rest/TestPolicyAuditProvider.java | 1 + ...estPolicyComponentsHealthCheckControllerV1.java | 39 ++-- .../TestPolicyComponentsHealthCheckProvider.java | 32 +-- .../pap/main/rest/TestPolicyStatusProvider.java | 1 + .../policy/pap/main/rest/TestProviderBase.java | 2 + .../onap/policy/pap/main/rest/e2e/End2EndBase.java | 6 +- .../policy/pap/main/rest/e2e/PolicyAuditTest.java | 21 +- .../policy/pap/main/rest/e2e/StatisticsTest.java | 13 +- .../onap/policy/pap/main/startstop/TestMain.java | 163 --------------- .../pap/main/startstop/TestPapActivator.java | 6 +- main/src/test/resources/config/application.yaml | 81 ++++++++ packages/policy-pap-docker/pom.xml | 8 +- .../policy-pap-docker/src/main/docker/Dockerfile | 8 +- .../src/main/docker/policy-pap.sh | 18 +- .../src/main/package/tarball/assembly.xml | 2 + .../src/main/resources/etc/defaultConfig.json | 84 -------- .../src/main/resources/etc/papParameters.yaml | 84 ++++++++ 68 files changed, 1376 insertions(+), 1638 deletions(-) create mode 100644 main/src/main/java/org/onap/policy/pap/main/PapExceptionHandler.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/PolicyPapApplication.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/config/PapAafConfig.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/config/WebSecurityConfig.java delete mode 100644 main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java delete mode 100644 main/src/main/java/org/onap/policy/pap/main/startstop/Main.java delete mode 100644 main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java create mode 100644 main/src/main/resources/application.yaml delete mode 100644 main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java delete mode 100644 main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java create mode 100644 main/src/test/resources/config/application.yaml delete mode 100644 packages/policy-pap-tarball/src/main/resources/etc/defaultConfig.json create mode 100644 packages/policy-pap-tarball/src/main/resources/etc/papParameters.yaml diff --git a/main/pom.xml b/main/pom.xml index b2868c92..dc77119f 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -2,7 +2,7 @@ ============LICENSE_START======================================================= Copyright (C) 2019 Nordix Foundation. Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. - Modifications Copyright (C) 2020 Bell Canada. + Modifications Copyright (C) 2020-2021 Bell Canada. ================================================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,27 +36,43 @@ - commons-cli - commons-cli + org.springframework.boot + spring-boot-starter-web - org.onap.policy.common - common-parameters - ${policy.common.version} + org.springframework.boot + spring-boot-starter-security - org.onap.policy.common - utils - ${policy.common.version} + org.springframework.boot + spring-boot-starter-aop + ${version.springboot} - org.onap.policy.common - policy-endpoints - ${policy.common.version} + org.springframework.boot + spring-boot-starter-actuator + ${version.springboot} + + + io.micrometer + micrometer-registry-prometheus + ${version.io.micrometer} + runtime + + + io.springfox + springfox-boot-starter + ${version.springfox} + + + io.springfox + springfox-swagger-ui + runtime + org.onap.policy.common - gson + policy-endpoints ${policy.common.version} @@ -74,11 +90,6 @@ policy-models-provider ${policy.models.version} - - org.projectlombok - lombok - provided - org.onap.policy.common utils-test @@ -91,15 +102,24 @@ test - org.assertj - assertj-core + com.h2database + h2 test - com.h2database - h2 + junit + junit + test + + + org.junit.vintage + junit-vintage-engine test + + org.springframework.boot + spring-boot-starter-test + @@ -120,5 +140,19 @@ + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + package + + + + \ No newline at end of file diff --git a/main/src/main/java/org/onap/policy/pap/main/PapExceptionHandler.java b/main/src/main/java/org/onap/policy/pap/main/PapExceptionHandler.java new file mode 100644 index 00000000..54418123 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/PapExceptionHandler.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main; + +import java.util.UUID; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.errors.concepts.ErrorResponse; +import org.onap.policy.pap.main.rest.PapRestControllerV1; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; + +@RestControllerAdvice +public class PapExceptionHandler { + + private static final Logger logger = LoggerFactory.getLogger(PapExceptionHandler.class); + + /** + * Handle PfModelException. + * + * @return ResponseEntity the response + */ + @ExceptionHandler(PfModelException.class) + public ResponseEntity pfModelExceptionHandler(PfModelException exp, WebRequest req) { + return handlePfModelException(exp, exp.getErrorResponse(), req); + } + + /** + * Handle PfModelRuntimeException. + * + * @return ResponseEntity the response + */ + @ExceptionHandler(PfModelRuntimeException.class) + public ResponseEntity pfModelRuntimeExceptionHandler(PfModelRuntimeException exp, WebRequest req) { + return handlePfModelException(exp, exp.getErrorResponse(), req); + } + + private ResponseEntity handlePfModelException(Exception exp, ErrorResponse errorResponse, + WebRequest req) { + logger.warn(exp.getMessage(), exp); + String requestId = req.getHeader(PapRestControllerV1.REQUEST_ID_NAME); + return PapRestControllerV1.addLoggingHeaders( + PapRestControllerV1 + .addVersionControlHeaders(ResponseEntity.status(errorResponse.getResponseCode().getStatusCode())), + requestId != null ? UUID.fromString(requestId) : null).body(errorResponse); + } + + /** + * Handle IllegalArgumentException. + * + * @return ResponseEntity the response + */ + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException exp, WebRequest req) { + String errorMessage = exp.getClass().getName() + " " + exp.getMessage(); + logger.warn(exp.getMessage(), exp); + String requestId = req.getHeader(PapRestControllerV1.REQUEST_ID_NAME); + return PapRestControllerV1.addLoggingHeaders( + PapRestControllerV1.addVersionControlHeaders(ResponseEntity.status(HttpStatus.BAD_REQUEST)), + requestId != null ? UUID.fromString(requestId) : null).body(errorMessage); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/PolicyPapApplication.java b/main/src/main/java/org/onap/policy/pap/main/PolicyPapApplication.java new file mode 100644 index 00000000..4a13c74d --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/PolicyPapApplication.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.onap.policy.common.gson.GsonMessageBodyHandler; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication(exclude = {JacksonAutoConfiguration.class}) +public class PolicyPapApplication { + + public static void main(String[] args) { + SpringApplication.run(PolicyPapApplication.class, args); + } + + @Bean + public Gson gson() { + return GsonMessageBodyHandler.configBuilder(new GsonBuilder()).create(); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpMessageGenerator.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpMessageGenerator.java index 8dad7ac4..02609535 100644 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpMessageGenerator.java +++ b/main/src/main/java/org/onap/policy/pap/main/comm/PdpMessageGenerator.java @@ -42,6 +42,8 @@ import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; /** @@ -52,25 +54,26 @@ public class PdpMessageGenerator { private static final String PAP_GROUP_PARAMS_NAME = "PapGroup"; + private boolean includeHeartBeat; /** * Lock used when updating PDPs. */ - protected final Object updateLock; + protected Object updateLock; /** * Used to send UPDATE and STATE-CHANGE requests to the PDPs. */ - protected final PdpModifyRequestMap requestMap; + protected PdpModifyRequestMap requestMap; /** * Factory for PAP DAO. */ - protected final PolicyModelsProviderFactoryWrapper modelProviderWrapper; + protected PolicyModelsProviderFactoryWrapper modelProviderWrapper; /** * Heart beat interval, in milliseconds, to pass to PDPs, or {@code null}. */ - private final Long heartBeatMs; + private Long heartBeatMs; /** * Constructs the object. @@ -79,6 +82,14 @@ public class PdpMessageGenerator { * PDP-UPDATE messages */ public PdpMessageGenerator(boolean includeHeartBeat) { + this.includeHeartBeat = includeHeartBeat; + } + + /** + * Initialize the parameters. + */ + @EventListener(ApplicationReadyEvent.class) + public void initialize() { modelProviderWrapper = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); updateLock = Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class); requestMap = Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class); diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandler.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandler.java index 4ffbe622..fa90266d 100644 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandler.java +++ b/main/src/main/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandler.java @@ -86,6 +86,7 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { */ public PdpStatusMessageHandler(PdpParameters params, boolean savePdpStatistics) { super(true); + super.initialize(); this.params = params; this.savePdpStatistics = savePdpStatistics; } diff --git a/main/src/main/java/org/onap/policy/pap/main/config/PapAafConfig.java b/main/src/main/java/org/onap/policy/pap/main/config/PapAafConfig.java new file mode 100644 index 00000000..d73a37d8 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/config/PapAafConfig.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.config; + +import javax.servlet.Filter; +import org.onap.policy.pap.main.rest.PapAafFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +@Configuration +@Profile(value = {"aaf-auth"}) +public class PapAafConfig { + + /** + * Method to return Pap Aaf filter. + * + * @return Filter papAafFilter + */ + @Bean + public Filter papAafFilter() { + return new PapAafFilter(); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/config/WebSecurityConfig.java b/main/src/main/java/org/onap/policy/pap/main/config/WebSecurityConfig.java new file mode 100644 index 00000000..4c344405 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/config/WebSecurityConfig.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().antMatchers().authenticated().anyRequest().authenticated().and().httpBasic(); + // disable csrf as the endpoints are meant for non browser clients + http.csrf().disable(); + } + +} diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java index f89e156c..4f08069f 100644 --- a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java +++ b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java @@ -24,14 +24,17 @@ package org.onap.policy.pap.main.parameters; import java.util.List; import lombok.Getter; +import lombok.Setter; import org.onap.policy.common.endpoints.parameters.RestClientParameters; -import org.onap.policy.common.endpoints.parameters.RestServerParameters; import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; import org.onap.policy.common.parameters.ParameterGroupImpl; import org.onap.policy.common.parameters.annotations.NotBlank; import org.onap.policy.common.parameters.annotations.NotNull; import org.onap.policy.common.parameters.annotations.Valid; +import org.onap.policy.common.parameters.validation.ParameterGroupConstraint; import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; /** * Class to hold all parameters needed for pap component. @@ -41,19 +44,28 @@ import org.onap.policy.models.provider.PolicyModelsProviderParameters; @NotNull @NotBlank @Getter +@Setter +@Configuration +@ConfigurationProperties(prefix = "pap") public class PapParameterGroup extends ParameterGroupImpl { @Valid - private RestServerParameters restServerParameters; - @Valid + @ParameterGroupConstraint private PdpParameters pdpParameters; @Valid + @ParameterGroupConstraint private PolicyModelsProviderParameters databaseProviderParameters; private boolean savePdpStatisticsInDb; @Valid + @ParameterGroupConstraint private TopicParameterGroup topicParameterGroup; // API, Distribution Health Check REST client parameters. + @ParameterGroupConstraint private List<@NotNull @Valid RestClientParameters> healthCheckRestClientParameters; + public PapParameterGroup() { + super(); + } + /** * Create the pap parameter group. * diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java deleted file mode 100644 index 2f53b9bc..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.parameters; - -import java.io.File; -import org.onap.policy.common.parameters.ValidationResult; -import org.onap.policy.common.utils.coder.Coder; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.pap.main.PolicyPapException; -import org.onap.policy.pap.main.startstop.PapCommandLineArguments; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class handles reading, parsing and validating of policy pap parameters from JSON files. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class PapParameterHandler { - - private static final Logger LOGGER = LoggerFactory.getLogger(PapParameterHandler.class); - - private static final Coder CODER = new StandardCoder(); - - /** - * Read the parameters from the parameter file. - * - * @param arguments the arguments passed to policy pap - * @return the parameters read from the configuration file - * @throws PolicyPapException on parameter exceptions - */ - public PapParameterGroup getParameters(final PapCommandLineArguments arguments) throws PolicyPapException { - PapParameterGroup papParameterGroup = null; - - // Read the parameters - try { - // Read the parameters from JSON - var file = new File(arguments.getFullConfigurationFilePath()); - papParameterGroup = CODER.decode(file, PapParameterGroup.class); - } catch (final CoderException e) { - final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() - + "\"\n" + "(" + e.getClass().getSimpleName() + ")"; - throw new PolicyPapException(errorMessage, e); - } - - // The JSON processing returns null if there is an empty file - if (papParameterGroup == null) { - final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; - LOGGER.error(errorMessage); - throw new PolicyPapException(errorMessage); - } - - // validate the parameters - final ValidationResult validationResult = papParameterGroup.validate(); - if (!validationResult.isValid()) { - String returnMessage = - "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; - returnMessage += validationResult.getResult(); - - LOGGER.error(returnMessage); - throw new PolicyPapException(returnMessage); - } - - return papParameterGroup; - } -} diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PdpParameters.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PdpParameters.java index 2f89eedd..b62acb68 100644 --- a/main/src/main/java/org/onap/policy/pap/main/parameters/PdpParameters.java +++ b/main/src/main/java/org/onap/policy/pap/main/parameters/PdpParameters.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +23,7 @@ package org.onap.policy.pap.main.parameters; import java.util.concurrent.TimeUnit; import lombok.Getter; +import lombok.Setter; import org.onap.policy.common.parameters.ParameterGroupImpl; import org.onap.policy.common.parameters.annotations.Min; import org.onap.policy.common.parameters.annotations.NotBlank; @@ -34,6 +36,7 @@ import org.onap.policy.common.parameters.annotations.Valid; @NotNull @NotBlank @Getter +@Setter public class PdpParameters extends ParameterGroupImpl { /** diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PdpRequestParameters.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PdpRequestParameters.java index 2df20fb3..44563a89 100644 --- a/main/src/main/java/org/onap/policy/pap/main/parameters/PdpRequestParameters.java +++ b/main/src/main/java/org/onap/policy/pap/main/parameters/PdpRequestParameters.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +22,7 @@ package org.onap.policy.pap.main.parameters; import lombok.Getter; +import lombok.Setter; import org.onap.policy.common.parameters.ParameterGroupImpl; import org.onap.policy.common.parameters.annotations.Min; import org.onap.policy.common.parameters.annotations.NotBlank; @@ -32,6 +34,7 @@ import org.onap.policy.common.parameters.annotations.NotNull; @NotNull @NotBlank @Getter +@Setter public class PdpRequestParameters extends ParameterGroupImpl { // NOTE: these fields must not be "private" or the validator will skip them diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckProvider.java index 4b9c6f70..dbbb49e8 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckProvider.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,12 +27,14 @@ import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.startstop.PapActivator; +import org.springframework.stereotype.Service; /** * Class to fetch health check of PAP service. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@Service public class HealthCheckProvider { private static final String NOT_ALIVE = "not alive"; diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckRestControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckRestControllerV1.java index 8cb3acfa..19e47646 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckRestControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckRestControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019,2021 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,27 +26,34 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Authorization; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; +import lombok.RequiredArgsConstructor; import org.onap.policy.common.endpoints.report.HealthCheckReport; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST endpoints for PAP component health check. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class HealthCheckRestControllerV1 extends PapRestControllerV1 { +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor +public class HealthCheckRestControllerV1 extends PapRestControllerV1 { - @GET - @Path("healthcheck") + private final HealthCheckProvider provider; + + @GetMapping("healthcheck") @ApiOperation(value = "Perform healthcheck", notes = "Returns healthy status of the Policy Administration component", response = HealthCheckReport.class, authorizations = @Authorization(value = AUTHORIZATION_TYPE)) @ApiResponses(value = {@ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE), @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)}) - public Response healthcheck() { - return Response.status(Response.Status.OK).entity(new HealthCheckProvider().performHealthCheck()).build(); + public ResponseEntity healthcheck() { + return ResponseEntity.ok().body(provider.performHealthCheck()); } + } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java index 2dab2996..5770f441 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +22,6 @@ package org.onap.policy.pap.main.rest; -import io.swagger.annotations.Api; import io.swagger.annotations.BasicAuthDefinition; import io.swagger.annotations.Info; import io.swagger.annotations.SecurityDefinition; @@ -29,13 +29,11 @@ import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; import java.net.HttpURLConnection; import java.util.UUID; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.SecurityContext; import org.onap.policy.models.base.PfModelException; +import org.springframework.http.ResponseEntity.BodyBuilder; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; /** * Version v1 common superclass to provide REST endpoints for PAP component. @@ -43,9 +41,6 @@ import org.onap.policy.models.base.PfModelException; * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ // @formatter:off -@Path("/policy/pap/v1") -@Api(value = "Policy Administration (PAP) API") -@Produces({MediaType.APPLICATION_JSON, PapRestControllerV1.APPLICATION_YAML}) @SwaggerDefinition( info = @Info(description = "Policy Administration is responsible for the deployment life cycle of policies as well as " @@ -97,16 +92,13 @@ public class PapRestControllerV1 { public static final String AUTHORIZATION_ERROR_MESSAGE = "Authorization Error"; public static final String SERVER_ERROR_MESSAGE = "Internal Server Error"; - @Context - SecurityContext securityContext; - /** * Adds version headers to the response. * * @param respBuilder response builder * @return the response builder, with version headers */ - public ResponseBuilder addVersionControlHeaders(ResponseBuilder respBuilder) { + public static BodyBuilder addVersionControlHeaders(BodyBuilder respBuilder) { return respBuilder.header(VERSION_MINOR_NAME, "0").header(VERSION_PATCH_NAME, "0").header(VERSION_LATEST_NAME, API_VERSION); } @@ -117,13 +109,13 @@ public class PapRestControllerV1 { * @param respBuilder response builder * @return the response builder, with version logging */ - public ResponseBuilder addLoggingHeaders(ResponseBuilder respBuilder, UUID requestId) { + public static BodyBuilder addLoggingHeaders(BodyBuilder respBuilder, UUID requestId) { if (requestId == null) { // Generate a random uuid if client does not embed requestId in rest request - return respBuilder.header(REQUEST_ID_NAME, UUID.randomUUID()); + return respBuilder.header(REQUEST_ID_NAME, UUID.randomUUID().toString()); } - return respBuilder.header(REQUEST_ID_NAME, requestId); + return respBuilder.header(REQUEST_ID_NAME, requestId.toString()); } /** @@ -131,8 +123,9 @@ public class PapRestControllerV1 { * @return username as {@link String} */ public String getPrincipal() { - if (securityContext != null) { - return securityContext.getUserPrincipal().getName(); + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null) { + return authentication.getName(); } return ""; } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupCreateOrUpdateControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupCreateOrUpdateControllerV1.java index 505f7fee..b588d08a 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupCreateOrUpdateControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupCreateOrUpdateControllerV1.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019,2021 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,25 +31,30 @@ import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.UUID; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import lombok.RequiredArgsConstructor; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpGroupUpdateResponse; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for PAP component to create or update PDP groups. */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class PdpGroupCreateOrUpdateControllerV1 extends PapRestControllerV1 { private static final Logger logger = LoggerFactory.getLogger(PdpGroupCreateOrUpdateControllerV1.class); - private final PdpGroupCreateOrUpdateProvider provider = new PdpGroupCreateOrUpdateProvider(); + private final PdpGroupCreateOrUpdateProvider provider; /** * Creates or updates one or more PDP groups. @@ -58,8 +64,7 @@ public class PdpGroupCreateOrUpdateControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @POST - @Path("pdps/groups/batch") + @PostMapping("pdps/groups/batch") @ApiOperation(value = "Create or update PDP Groups", notes = "Create or update one or more PDP Groups, returning optional error details", response = PdpGroupUpdateResponse.class, @@ -88,9 +93,11 @@ public class PdpGroupCreateOrUpdateControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response createOrUpdateGroups( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "List of PDP Group Configuration", required = true) PdpGroups groups) { + public ResponseEntity createOrUpdateGroups( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "List of PDP Group Configuration", required = true) @RequestBody PdpGroups groups) { return doOperation(requestId, "create groups failed", () -> provider.createOrUpdateGroups(groups)); } @@ -103,18 +110,19 @@ public class PdpGroupCreateOrUpdateControllerV1 extends PapRestControllerV1 { * @param runnable operation to invoke * @return a {@link PdpGroupUpdateResponse} response entity */ - private Response doOperation(UUID requestId, String errmsg, RunnableWithPfEx runnable) { + private ResponseEntity doOperation(UUID requestId, String errmsg, + RunnableWithPfEx runnable) { try { runnable.run(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId) - .entity(new PdpGroupUpdateResponse()).build(); - + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(new PdpGroupUpdateResponse()); } catch (PfModelException | PfModelRuntimeException e) { logger.warn(errmsg, e); var resp = new PdpGroupUpdateResponse(); resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(resp).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(resp); } } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupCreateOrUpdateProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupCreateOrUpdateProvider.java index 696cc8c0..ce7fdaa7 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupCreateOrUpdateProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupCreateOrUpdateProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,6 +50,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.PapConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; /** * Provider for PAP component to create or update PDP groups. The following items must be in the @@ -59,16 +61,10 @@ import org.slf4j.LoggerFactory; *
  • PAP DAO Factory
  • * */ +@Service public class PdpGroupCreateOrUpdateProvider extends ProviderBase { private static final Logger logger = LoggerFactory.getLogger(PdpGroupCreateOrUpdateProvider.class); - /** - * Constructs the object. - */ - public PdpGroupCreateOrUpdateProvider() { - super(); - } - /** * Creates or updates PDP groups. * diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java index 12916769..7853fda6 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java @@ -31,12 +31,7 @@ import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.UUID; -import javax.ws.rs.DELETE; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import lombok.RequiredArgsConstructor; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; @@ -44,14 +39,23 @@ import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for PAP component to delete a PDP group. */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeleteControllerV1.class); - private final PdpGroupDeleteProvider provider = new PdpGroupDeleteProvider(); + private final PdpGroupDeleteProvider provider; /** * Deletes a PDP group. @@ -61,8 +65,7 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @DELETE - @Path("pdps/groups/{name}") + @DeleteMapping("pdps/groups/{name}") @ApiOperation(value = "Delete PDP Group", notes = "Deletes a PDP Group, returning optional error details", response = PdpGroupDeleteResponse.class, @@ -90,10 +93,11 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on - - public Response deleteGroup(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "PDP Group Name", required = true) @PathParam("name") String groupName) { - + public ResponseEntity deleteGroup( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "PDP Group Name") @PathVariable("name") String groupName) { return doOperation(requestId, "delete group failed", () -> provider.deleteGroup(groupName)); } @@ -105,8 +109,7 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @DELETE - @Path("pdps/policies/{name}") + @DeleteMapping("pdps/policies/{name}") @ApiOperation(value = "Undeploy a PDP Policy from PDPs", notes = "Undeploys the latest version of a policy from the PDPs, returning optional error details", response = PdpGroupDeployResponse.class, @@ -134,9 +137,11 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on - - public Response deletePolicy(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "PDP Policy Name", required = true) @PathParam("name") String policyName) { + public ResponseEntity deletePolicy( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "PDP Policy Name") @PathVariable("name") String policyName) { return doUndeployOperation(requestId, "undeploy policy failed", () -> provider.undeploy(new ToscaConceptIdentifierOptVersion(policyName, null), getPrincipal())); @@ -151,8 +156,7 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @DELETE - @Path("pdps/policies/{name}/versions/{version}") + @DeleteMapping("pdps/policies/{name}/versions/{version}") @ApiOperation(value = "Undeploy version of a PDP Policy from PDPs", notes = "Undeploys a specific version of a policy from the PDPs, returning optional error details", response = PdpGroupDeployResponse.class, @@ -180,11 +184,12 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on - - public Response deletePolicyVersion( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "PDP Policy Name", required = true) @PathParam("name") String policyName, - @ApiParam(value = "PDP Policy Version", required = true) @PathParam("version") String version) { + public ResponseEntity deletePolicyVersion( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "PDP Policy Name") @PathVariable("name") String policyName, + @ApiParam(value = "PDP Policy Version") @PathVariable("version") String version) { return doUndeployOperation(requestId, "undeploy policy failed", () -> provider.undeploy(new ToscaConceptIdentifierOptVersion(policyName, version), getPrincipal())); @@ -198,18 +203,20 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { * @param runnable operation to invoke * @return a {@link PdpGroupDeleteResponse} response entity */ - private Response doOperation(UUID requestId, String errmsg, RunnableWithPfEx runnable) { + private ResponseEntity doOperation(UUID requestId, String errmsg, + RunnableWithPfEx runnable) { try { runnable.run(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId) - .entity(new PdpGroupDeleteResponse()).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(new PdpGroupDeleteResponse()); } catch (PfModelException | PfModelRuntimeException e) { logger.warn(errmsg, e); var resp = new PdpGroupDeleteResponse(); resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(resp).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(resp); } } @@ -221,20 +228,21 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { * @param runnable operation to invoke * @return a {@link PdpGroupDeployResponse} response entity */ - private Response doUndeployOperation(UUID requestId, String errmsg, RunnableWithPfEx runnable) { + private ResponseEntity doUndeployOperation(UUID requestId, String errmsg, + RunnableWithPfEx runnable) { try { runnable.run(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.ACCEPTED)), requestId) - .entity(new PdpGroupDeployResponse(PdpGroupDeployControllerV1.DEPLOYMENT_RESPONSE_MSG, - PdpGroupDeployControllerV1.POLICY_STATUS_URI)) - .build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.accepted()), requestId) + .body(new PdpGroupDeployResponse(PdpGroupDeployControllerV1.DEPLOYMENT_RESPONSE_MSG, + PdpGroupDeployControllerV1.POLICY_STATUS_URI)); } catch (PfModelException | PfModelRuntimeException e) { logger.warn(errmsg, e); var resp = new PdpGroupDeployResponse(); resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(resp).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(resp); } } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java index 6f39a715..1a04e061 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,21 +36,15 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierO import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; /** * Provider for PAP component to delete PDP groups. */ +@Service public class PdpGroupDeleteProvider extends ProviderBase { private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeleteProvider.class); - - /** - * Constructs the object. - */ - public PdpGroupDeleteProvider() { - super(); - } - /** * Deletes a PDP group. * diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java index 86d730f2..d1e732d5 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,11 +31,7 @@ import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.UUID; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import lombok.RequiredArgsConstructor; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpDeployPolicies; @@ -43,10 +39,19 @@ import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; import org.onap.policy.models.pdp.concepts.DeploymentGroups; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for PAP component to deploy a PDP group. */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { public static final String POLICY_STATUS_URI = "/policy/pap/v1/policies/status"; @@ -56,7 +61,7 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeployControllerV1.class); - private final PdpGroupDeployProvider provider = new PdpGroupDeployProvider(); + private final PdpGroupDeployProvider provider; /** * Updates policy deployments within specific PDP groups. @@ -66,8 +71,7 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @POST - @Path("pdps/deployments/batch") + @PostMapping("pdps/deployments/batch") @ApiOperation(value = "Updates policy deployments within specific PDP groups", notes = "Updates policy deployments within specific PDP groups, returning optional error details", response = PdpGroupDeployResponse.class, @@ -95,10 +99,11 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on - - public Response updateGroupPolicies( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "List of PDP Group Deployments", required = true) DeploymentGroups groups) { + public ResponseEntity updateGroupPolicies( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "List of PDP Group Deployments", required = true) @RequestBody DeploymentGroups groups) { return doOperation(requestId, "update policy deployments failed", () -> provider.updateGroupPolicies(groups, getPrincipal())); } @@ -111,8 +116,7 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @POST - @Path("pdps/policies") + @PostMapping("pdps/policies") @ApiOperation(value = "Deploy or update PDP Policies", notes = "Deploys or updates PDP Policies, returning optional error details", response = PdpGroupDeployResponse.class, @@ -140,9 +144,11 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on - - public Response deployPolicies(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "PDP Policies; only the name is required", required = true) PdpDeployPolicies policies) { + public ResponseEntity deployPolicies( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "PDP Policies; only the name is required") @RequestBody PdpDeployPolicies policies) { return doOperation(requestId, "deploy policies failed", () -> provider.deployPolicies(policies, getPrincipal())); } @@ -155,18 +161,21 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { * @param runnable operation to invoke * @return a {@link PdpGroupDeployResponse} response entity */ - private Response doOperation(UUID requestId, String errmsg, RunnableWithPfEx runnable) { + private ResponseEntity doOperation(UUID requestId, String errmsg, + RunnableWithPfEx runnable) { try { runnable.run(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.ACCEPTED)), requestId) - .entity(new PdpGroupDeployResponse(DEPLOYMENT_RESPONSE_MSG, POLICY_STATUS_URI)).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.accepted()), requestId) + .body(new PdpGroupDeployResponse(DEPLOYMENT_RESPONSE_MSG, POLICY_STATUS_URI)); } catch (PfModelException | PfModelRuntimeException e) { logger.warn(errmsg, e); var resp = new PdpGroupDeployResponse(); resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(resp).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(resp); } } + } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java index 151e5145..5277ca69 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,6 +58,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierO import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; /** * Provider for PAP component to deploy PDP groups. The following items must be in the @@ -67,20 +69,13 @@ import org.slf4j.LoggerFactory; *
  • PAP DAO Factory
  • * */ +@Service public class PdpGroupDeployProvider extends ProviderBase { private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeployProvider.class); private static final StandardCoder coder = new StandardCoder(); private static final String POLICY_RESULT_NAME = "policy"; - - /** - * Constructs the object. - */ - public PdpGroupDeployProvider() { - super(); - } - /** * Updates policies in specific PDP groups. * @@ -413,7 +408,6 @@ public class PdpGroupDeployProvider extends ProviderBase { private void deploySimplePolicies(SessionData data, PdpDeployPolicies policies) throws PfModelException { for (ToscaConceptIdentifierOptVersion desiredPolicy : policies.getPolicies()) { - try { processPolicy(data, desiredPolicy); diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckControllerV1.java index 300d3c72..ccc2ba1f 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019,2021 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,28 +31,29 @@ import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.UUID; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.Pdps; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end point for PAP component to fetch health status of all PDPs registered with PAP. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class PdpGroupHealthCheckControllerV1 extends PapRestControllerV1 { - private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupHealthCheckControllerV1.class); +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor +public class PdpGroupHealthCheckControllerV1 extends PapRestControllerV1 { - private final PdpGroupHealthCheckProvider provider = new PdpGroupHealthCheckProvider(); + private final PdpGroupHealthCheckProvider provider; /** * Returns health status of all PDPs registered with PAP. @@ -60,8 +62,7 @@ public class PdpGroupHealthCheckControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @GET - @Path("pdps/healthcheck") + @GetMapping("pdps/healthcheck") @ApiOperation(value = "Returns health status of all PDPs registered with PAP", notes = "Queries health status of all PDPs, returning all pdps health status", response = Pdps.class, @@ -89,19 +90,11 @@ public class PdpGroupHealthCheckControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on - - public Response pdpGroupHealthCheck( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { - - try { - final Pair pair = provider.fetchPdpGroupHealthStatus(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); - } catch (final PfModelException | PfModelRuntimeException exp) { - LOGGER.info("pdpGroup health check failed", exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), requestId) - .entity(exp.getErrorResponse()).build(); - } + public ResponseEntity pdpGroupHealthCheck(@ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) throws PfModelException { + Pair pair = provider.fetchPdpGroupHealthStatus(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(pair.getLeft())), requestId) + .body(pair.getRight()); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckProvider.java index ce820f08..74a89046 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckProvider.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +24,6 @@ package org.onap.policy.pap.main.rest; import java.util.ArrayList; import java.util.List; -import javax.ws.rs.core.Response; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; @@ -36,12 +36,15 @@ import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; /** * Provider for PAP component to to fetch health status of all PDPs registered with PAP. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@Service public class PdpGroupHealthCheckProvider { private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupHealthCheckProvider.class); @@ -52,7 +55,7 @@ public class PdpGroupHealthCheckProvider { * @return a pair containing the status and the response * @throws PfModelException in case of errors */ - public Pair fetchPdpGroupHealthStatus() throws PfModelException { + public Pair fetchPdpGroupHealthStatus() throws PfModelException { final var pdps = new Pdps(); final PolicyModelsProviderFactoryWrapper modelProviderWrapper = @@ -68,6 +71,6 @@ public class PdpGroupHealthCheckProvider { pdps.setPdpList(pdpList); } LOGGER.debug("PdpGroup HealthCheck Response - {}", pdps); - return Pair.of(Response.Status.OK, pdps); + return Pair.of(HttpStatus.OK, pdps); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryControllerV1.java index 576eb8d8..03a853ba 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019,2021 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,38 +31,38 @@ import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.UUID; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpGroups; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for PAP component to query details of all PDP groups. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class PdpGroupQueryControllerV1 extends PapRestControllerV1 { - private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupQueryControllerV1.class); - - private final PdpGroupQueryProvider provider = new PdpGroupQueryProvider(); + private final PdpGroupQueryProvider provider; /** * Queries details of all PDP groups. * * @param requestId request ID used in ONAP logging * @return a response + * @throws PfModelException the exception */ // @formatter:off - @GET - @Path("pdps") + @GetMapping("pdps") @ApiOperation(value = "Query details of all PDP groups", notes = "Queries details of all PDP groups, returning all group details", response = PdpGroups.class, @@ -89,19 +90,12 @@ public class PdpGroupQueryControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on + public ResponseEntity queryGroupDetails(@ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) throws PfModelException { - public Response queryGroupDetails( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { - - try { - final Pair pair = provider.fetchPdpGroupDetails(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); - } catch (final PfModelException | PfModelRuntimeException exp) { - LOGGER.info("group query failed", exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), requestId) - .entity(exp.getErrorResponse()).build(); - } + final Pair pair = provider.fetchPdpGroupDetails(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(pair.getLeft())), requestId) + .body(pair.getRight()); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryProvider.java index 3edc38af..f1a22f50 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryProvider.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +22,6 @@ package org.onap.policy.pap.main.rest; -import javax.ws.rs.core.Response; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; @@ -31,12 +31,15 @@ import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; /** * Provider for PAP component to query details of all PDP groups. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@Service public class PdpGroupQueryProvider { private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupQueryProvider.class); @@ -47,7 +50,7 @@ public class PdpGroupQueryProvider { * @return a pair containing the status and the response * @throws PfModelException in case of errors */ - public Pair fetchPdpGroupDetails() throws PfModelException { + public Pair fetchPdpGroupDetails() throws PfModelException { final var pdpGroups = new PdpGroups(); final PolicyModelsProviderFactoryWrapper modelProviderWrapper = @@ -56,6 +59,6 @@ public class PdpGroupQueryProvider { pdpGroups.setGroups(databaseProvider.getPdpGroups(null)); } LOGGER.debug("PdpGroup Query Response - {}", pdpGroups); - return Pair.of(Response.Status.OK, pdpGroups); + return Pair.of(HttpStatus.OK, pdpGroups); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeControllerV1.java index 31574ab1..38df5a5d 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,31 +31,31 @@ import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.UUID; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpGroupStateChangeResponse; import org.onap.policy.models.pdp.enums.PdpState; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for PAP component to change state of a PDP group. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class PdpGroupStateChangeControllerV1 extends PapRestControllerV1 { - private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupStateChangeControllerV1.class); - - private final PdpGroupStateChangeProvider provider = new PdpGroupStateChangeProvider(); + private final PdpGroupStateChangeProvider provider; /** * Changes state of a PDP group. @@ -63,10 +64,10 @@ public class PdpGroupStateChangeControllerV1 extends PapRestControllerV1 { * @param groupName name of the PDP group to be deleted * @param state state of the PDP group * @return a response + * @throws PfModelException the exception */ // @formatter:off - @PUT - @Path("pdps/groups/{name}") + @PutMapping("pdps/groups/{name}") @ApiOperation(value = "Change state of a PDP Group", notes = "Changes state of PDP Group, returning optional error details", response = PdpGroupStateChangeResponse.class, @@ -93,21 +94,15 @@ public class PdpGroupStateChangeControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on + public ResponseEntity changeGroupState( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "PDP Group Name") @PathVariable("name") String groupName, + @ApiParam(value = "PDP Group State") @RequestParam("state") final PdpState state) throws PfModelException { - public Response changeGroupState( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "PDP Group Name", required = true) @PathParam("name") final String groupName, - @ApiParam(value = "PDP Group State", required = true) @QueryParam("state") final PdpState state) { - - try { - final Pair pair = provider.changeGroupState(groupName, state); - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); - } catch (final PfModelException | PfModelRuntimeException exp) { - LOGGER.info("group state-change failed", exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), requestId) - .entity(exp.getErrorResponse()).build(); - } + final Pair pair = provider.changeGroupState(groupName, state); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(pair.getLeft())), requestId) + .body(pair.getRight()); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeProvider.java index c8f67d75..5aaaf4ab 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeProvider.java @@ -36,12 +36,15 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.comm.PdpMessageGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; /** * Provider for PAP component to change state of PDP group. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@Service public class PdpGroupStateChangeProvider extends PdpMessageGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupStateChangeProvider.class); @@ -61,7 +64,7 @@ public class PdpGroupStateChangeProvider extends PdpMessageGenerator { * @return a pair containing the status and the response * @throws PfModelException in case of errors */ - public Pair changeGroupState(final String groupName, + public Pair changeGroupState(final String groupName, final PdpState pdpGroupState) throws PfModelException { synchronized (updateLock) { switch (pdpGroupState) { @@ -75,7 +78,7 @@ public class PdpGroupStateChangeProvider extends PdpMessageGenerator { throw new PfModelException(Response.Status.BAD_REQUEST, "Only ACTIVE or PASSIVE state changes are allowed"); } - return Pair.of(Response.Status.OK, new PdpGroupStateChangeResponse()); + return Pair.of(HttpStatus.OK, new PdpGroupStateChangeResponse()); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java index a76afc2b..e195a79b 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java @@ -29,30 +29,31 @@ import io.swagger.annotations.ResponseHeader; import java.time.Instant; import java.util.Collection; import java.util.UUID; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; +import lombok.RequiredArgsConstructor; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for PAP component to retrieve the audit information for * various operations on policies. */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class PolicyAuditControllerV1 extends PapRestControllerV1 { - private static final Logger logger = LoggerFactory.getLogger(PolicyAuditControllerV1.class); - private static final String GET_AUDIT_RECORD_FAILED = "get audit records failed"; public static final String NO_AUDIT_RECORD_FOUND = "No records found matching the input parameters"; - private final PolicyAuditProvider provider = new PolicyAuditProvider(); + private final PolicyAuditProvider provider; /** * Queries audit information of all policies. @@ -62,10 +63,10 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { * @param startTime the starting time for the query in epoch timestamp * @param endTime the ending time for the query in epoch timestamp * @return a response + * @throws PfModelException the exception */ // @formatter:off - @GET - @Path("policies/audit") + @GetMapping("policies/audit") @ApiOperation(value = "Queries audit information for all the policies", notes = "Queries audit information for all the policies, " + "returning audit information for all the policies in the database", @@ -94,29 +95,25 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on + public ResponseEntity> getAllAuditRecords( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "Record count between 1-100") @RequestParam( + defaultValue = "10", + required = false, + value = "recordCount") final int recordCount, + @ApiParam(value = "Start time in epoch timestamp") @RequestParam( + required = false, + value = "startTime") final Long startTime, + @ApiParam(value = "End time in epoch timestamp") @RequestParam( + required = false, + value = "endTime") final Long endTime) + throws PfModelException { - public Response getAllAuditRecords( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "Record count between 1-100", - required = false) @QueryParam("recordCount") final int recordCount, - @ApiParam(value = "Start time in epoch timestamp", - required = false) @QueryParam("startTime") final Long startTime, - @ApiParam(value = "End time in epoch timestamp", - required = false) @QueryParam("endTime") final Long endTime) { - - try { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount) - .fromDate(convertEpochtoInstant(startTime)) - .toDate(convertEpochtoInstant(endTime)).build())) - .build(); - - } catch (PfModelException | PfModelRuntimeException exp) { - logger.warn(GET_AUDIT_RECORD_FAILED, exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), - requestId).entity(exp.getErrorResponse().getErrorMessage()).build(); - } + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount) + .fromDate(convertEpochtoInstant(startTime)).toDate(convertEpochtoInstant(endTime)).build())); } /** @@ -128,10 +125,10 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { * @param endTime the ending time for the query in epoch timestamp * @param pdpGroupName the pdp group name for the query * @return a response + * @throws PfModelException the exception */ // @formatter:off - @GET - @Path("policies/audit/{pdpGroupName}") + @GetMapping("policies/audit/{pdpGroupName}") @ApiOperation(value = "Queries audit information for all the policies in a PdpGroup", notes = "Queries audit information for all the policies in a PdpGroup, " + "returning audit information for all the policies belonging to the PdpGroup", @@ -160,30 +157,26 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on + public ResponseEntity getAuditRecordsByGroup( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "Record count between 1-100") @RequestParam( + defaultValue = "10", + required = false, + value = "recordCount") final int recordCount, + @ApiParam(value = "Start time in epoch timestamp") @RequestParam( + required = false, + value = "startTime") final Long startTime, + @ApiParam(value = "End time in epoch timestamp") @RequestParam( + required = false, + value = "endTime") final Long endTime, + @ApiParam(value = "PDP Group Name") @PathVariable("pdpGroupName") String pdpGroupName) throws PfModelException { - public Response getAuditRecordsByGroup( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "Record count between 1-100", - required = false) @QueryParam("recordCount") final int recordCount, - @ApiParam(value = "Start time in epoch timestamp", - required = false) @QueryParam("startTime") final Long startTime, - @ApiParam(value = "End time in epoch timestamp", - required = false) @QueryParam("endTime") final Long endTime, - @ApiParam(value = "PDP Group Name", - required = true) @PathParam("pdpGroupName") String pdpGroupName) { - - try { - return makeOkOrNotFoundResponse(requestId, - provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount) - .fromDate((convertEpochtoInstant(startTime))) - .toDate(convertEpochtoInstant(endTime)).pdpGroup(pdpGroupName).build())); - - } catch (PfModelException | PfModelRuntimeException exp) { - logger.warn(GET_AUDIT_RECORD_FAILED, exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), - requestId).entity(exp.getErrorResponse().getErrorMessage()).build(); - } + return makeOkOrNotFoundResponse(requestId, + provider.getAuditRecords( + AuditFilter.builder().recordNum(recordCount).fromDate((convertEpochtoInstant(startTime))) + .toDate(convertEpochtoInstant(endTime)).pdpGroup(pdpGroupName).build())); } /** @@ -197,10 +190,10 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { * @param policyName name of the Policy * @param policyVersion version of the Policy * @return a response + * @throws PfModelException the exception */ // @formatter:off - @GET - @Path("policies/audit/{pdpGroupName}/{policyName}/{policyVersion}") + @GetMapping("policies/audit/{pdpGroupName}/{policyName}/{policyVersion}") @ApiOperation(value = "Queries audit information for a specific version of a policy in a PdpGroup", notes = "Queries audit information for a specific version of a policy in a PdpGroup," + " returning audit information for the policy belonging to the PdpGroup", @@ -230,32 +223,29 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response getAuditRecordsOfPolicy( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "Record count between 1-100", - required = false) @QueryParam("recordCount") final int recordCount, - @ApiParam(value = "Start time in epoch timestamp", - required = false) @QueryParam("startTime") final Long startTime, - @ApiParam(value = "End time in epoch timestamp", - required = false) @QueryParam("endTime") final Long endTime, - @ApiParam(value = "PDP Group Name", required = true) @PathParam("pdpGroupName") String pdpGroupName, - @ApiParam(value = "Policy Name", required = true) @PathParam("policyName") String policyName, - @ApiParam(value = "Policy Version", - required = true) @PathParam("policyVersion") String policyVersion) { - - try { - return makeOkOrNotFoundResponse(requestId, - provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount) - .fromDate(convertEpochtoInstant(startTime)) - .toDate(convertEpochtoInstant(endTime)).pdpGroup(pdpGroupName) - .name(policyName).version(policyVersion).build())); + public ResponseEntity getAuditRecordsOfPolicy( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "Record count between 1-100", required = false) @RequestParam( + defaultValue = "10", + required = false, + value = "recordCount") final int recordCount, + @ApiParam(value = "Start time in epoch timestamp", required = false) @RequestParam( + required = false, + value = "startTime") final Long startTime, + @ApiParam(value = "End time in epoch timestamp") @RequestParam( + required = false, + value = "endTime") final Long endTime, + @ApiParam(value = "PDP Group Name") @PathVariable("pdpGroupName") String pdpGroupName, + @ApiParam(value = "Policy Name") @PathVariable("policyName") String policyName, + @ApiParam(value = "Policy Version") @PathVariable(value = "policyVersion") String policyVersion) + throws PfModelException { - } catch (PfModelException | PfModelRuntimeException exp) { - logger.warn(GET_AUDIT_RECORD_FAILED, exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), - requestId).entity(exp.getErrorResponse().getErrorMessage()).build(); - } + return makeOkOrNotFoundResponse(requestId, + provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount) + .fromDate(convertEpochtoInstant(startTime)).toDate(convertEpochtoInstant(endTime)) + .pdpGroup(pdpGroupName).name(policyName).version(policyVersion).build())); } /** @@ -268,10 +258,10 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { * @param policyName name of the Policy * @param policyVersion version of the Policy * @return a response + * @throws PfModelException the exception */ // @formatter:off - @GET - @Path("policies/audit/{policyName}/{policyVersion}") + @GetMapping("policies/audit/{policyName}/{policyVersion}") @ApiOperation(value = "Queries audit information for a specific version of a policy", notes = "Queries audit information for a specific version of a policy," + " returning audit information for the policy", @@ -301,38 +291,37 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response getAuditRecordsOfPolicy( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "Record count between 1-100", - required = false) @QueryParam("recordCount") final int recordCount, - @ApiParam(value = "Start time in epoch timestamp", - required = false) @QueryParam("startTime") final Long startTime, - @ApiParam(value = "End time in epoch timestamp", - required = false) @QueryParam("endTime") final Long endTime, - @ApiParam(value = "Policy Name", required = true) @PathParam("policyName") String policyName, - @ApiParam(value = "Policy Version", - required = true) @PathParam("policyVersion") String policyVersion) { + public ResponseEntity getAuditRecordsOfPolicy( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "Record count between 1-100") @RequestParam( + defaultValue = "10", + required = false, + value = "recordCount") final int recordCount, + @ApiParam(value = "Start time in epoch timestamp") @RequestParam( + required = false, + value = "startTime") final Long startTime, + @ApiParam(value = "End time in epoch timestamp") @RequestParam( + required = false, + value = "endTime") final Long endTime, + @ApiParam(value = "Policy Name") @PathVariable(required = true, value = "policyName") String policyName, + @ApiParam( + value = "Policy Version") @PathVariable(required = true, value = "policyVersion") String policyVersion) + throws PfModelException { - try { - return makeOkOrNotFoundResponse(requestId, provider.getAuditRecords(AuditFilter.builder() - .recordNum(recordCount).fromDate(convertEpochtoInstant(startTime)) - .toDate(convertEpochtoInstant(endTime)).name(policyName).version(policyVersion).build())); - - } catch (PfModelException | PfModelRuntimeException exp) { - logger.warn(GET_AUDIT_RECORD_FAILED, exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), - requestId).entity(exp.getErrorResponse().getErrorMessage()).build(); - } + return makeOkOrNotFoundResponse(requestId, + provider + .getAuditRecords(AuditFilter.builder().recordNum(recordCount).fromDate(convertEpochtoInstant(startTime)) + .toDate(convertEpochtoInstant(endTime)).name(policyName).version(policyVersion).build())); } - private Response makeOkOrNotFoundResponse(UUID requestId, Collection result) { + private ResponseEntity makeOkOrNotFoundResponse(UUID requestId, Collection result) { if (result.isEmpty()) { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.NOT_FOUND)), requestId) - .entity(NO_AUDIT_RECORD_FOUND).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.NOT_FOUND)), requestId) + .body(NO_AUDIT_RECORD_FOUND); } else { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(result).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(result); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java index 6da8b07f..c3c77a4a 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java @@ -26,22 +26,23 @@ import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.Audit import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Service; /** * Provider for PAP component to query policy audit information. */ +@Service public class PolicyAuditProvider { /** * Factory for PAP DAO. */ - private final PolicyModelsProviderFactoryWrapper daoFactory; + private PolicyModelsProviderFactoryWrapper daoFactory; - - /** - * Constructs the object. - */ - public PolicyAuditProvider() { + @EventListener(ApplicationReadyEvent.class) + public void initialize() { this.daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckControllerV1.java index 4e9a827f..f7787fc7 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019,2021 Nordix Foundation. * Modifications Copyright (C) 2020 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,13 +32,14 @@ import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.Map; import java.util.UUID; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.tuple.Pair; -import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end point for PAP component to fetch all policy components, including PAP, @@ -45,18 +47,13 @@ import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; * * @author Yehui Wang (yehui.wang@est.tech) */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class PolicyComponentsHealthCheckControllerV1 extends PapRestControllerV1 { - private PolicyComponentsHealthCheckProvider provider; + private final PolicyComponentsHealthCheckProvider provider; - /** - * Constructs the object. - * - * @throws HttpClientConfigException if creating http client failed - */ - public PolicyComponentsHealthCheckControllerV1() throws HttpClientConfigException { - provider = new PolicyComponentsHealthCheckProvider(); - } /** * Returns health status of all Policy components, including PAP, API, Distribution, and PDPs. @@ -65,8 +62,7 @@ public class PolicyComponentsHealthCheckControllerV1 extends PapRestControllerV1 * @return a response */ // @formatter:off - @GET - @Path("components/healthcheck") + @GetMapping("components/healthcheck") @ApiOperation(value = "Returns health status of all policy components, including PAP, API, Distribution, and PDPs", notes = "Queries health status of all policy components, returning all policy components health status", response = Map.class, @@ -94,12 +90,12 @@ public class PolicyComponentsHealthCheckControllerV1 extends PapRestControllerV1 @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) // @formatter:on - - public Response policyComponentsHealthCheck( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { - final Pair> pair = - provider.fetchPolicyComponentsHealthStatus(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); + public ResponseEntity> policyComponentsHealthCheck( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) { + final Pair> pair = provider.fetchPolicyComponentsHealthStatus(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(pair.getLeft())), requestId) + .body(pair.getRight()); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckProvider.java index 2eceb4b0..7a490166 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckProvider.java @@ -36,15 +36,17 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.regex.Pattern; import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; import org.onap.policy.common.endpoints.parameters.RestClientParameters; import org.onap.policy.common.endpoints.report.HealthCheckReport; -import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; @@ -58,33 +60,41 @@ import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; /** * Provider for PAP to fetch health status of all Policy components, including PAP, API, Distribution, and PDPs. * * @author Yehui Wang (yehui.wang@est.tech) */ +@Service public class PolicyComponentsHealthCheckProvider { private static final Logger LOGGER = LoggerFactory.getLogger(PolicyComponentsHealthCheckProvider.class); - private static final String PAP_GROUP_PARAMS_NAME = "PapGroup"; private static final String HEALTH_STATUS = "healthy"; private static final Pattern IP_REPLACEMENT_PATTERN = Pattern.compile("//(\\S+):"); private static final String POLICY_PAP_HEALTHCHECK_URI = "/policy/pap/v1/healthcheck"; private static List clients = new ArrayList<>(); - private static ExecutorService clientHealthCheckExecutorService; + private ExecutorService clientHealthCheckExecutorService; - private PapParameterGroup papParameterGroup = ParameterService.get(PAP_GROUP_PARAMS_NAME); + @Autowired + private PapParameterGroup papParameterGroup; + + @Value("${server.ssl.enabled:false}") + private boolean isHttps; + + @Value("${server.port}") + private int port; /** * This method is used to initialize clients and executor. - * @param papParameterGroup - * @{link PapParameterGroup} contains the Pap Parameters set during startup - * @param clientFactory - * @{link HttpClientFactory} contains the client details */ - public static void initializeClientHealthCheckExecutorService(PapParameterGroup papParameterGroup, - HttpClientFactory clientFactory) throws HttpClientConfigException { + @PostConstruct + public void initializeClientHealthCheckExecutorService() throws HttpClientConfigException { + HttpClientFactory clientFactory = HttpClientFactoryInstance.getClientFactory(); for (RestClientParameters params : papParameterGroup.getHealthCheckRestClientParameters()) { params.setManaged(false); clients.add(clientFactory.build(params)); @@ -92,12 +102,21 @@ public class PolicyComponentsHealthCheckProvider { clientHealthCheckExecutorService = Executors.newFixedThreadPool(clients.isEmpty() ? 1 : clients.size()); } + /** + * This method clears clients {@link List} and clientHealthCheckExecutorService {@link ExecutorService}. + */ + @PreDestroy + public void cleanup() { + clients.clear(); + clientHealthCheckExecutorService.shutdown(); + } + /** * Returns health status of all Policy components. * * @return a pair containing the status and the response */ - public Pair> fetchPolicyComponentsHealthStatus() { + public Pair> fetchPolicyComponentsHealthStatus() { boolean isHealthy; Map result; @@ -129,10 +148,8 @@ public class PolicyComponentsHealthCheckProvider { // Check PAP itself HealthCheckReport papReport = new HealthCheckProvider().performHealthCheck(); - var restServerParameters = papParameterGroup.getRestServerParameters(); - papReport.setUrl( - (restServerParameters.isHttps() ? "https://" : "http://") + papReport.getUrl() + ":" + restServerParameters - .getPort() + POLICY_PAP_HEALTHCHECK_URI); + papReport + .setUrl(isHttps ? "https://" : "http://" + papReport.getUrl() + ":" + port + POLICY_PAP_HEALTHCHECK_URI); if (!papReport.isHealthy()) { isHealthy = false; } @@ -154,7 +171,7 @@ public class PolicyComponentsHealthCheckProvider { result.put(HEALTH_STATUS, isHealthy); LOGGER.debug("Policy Components HealthCheck Response - {}", result); - return Pair.of(Status.OK, result); + return Pair.of(HttpStatus.OK, result); } private Map> fetchPdpsHealthStatus(List groups) { @@ -246,11 +263,4 @@ public class PolicyComponentsHealthCheckProvider { topicVerificationStatus, message); } - /** - * This method clears clients {@link List} and clientHealthCheckExecutorService {@link ExecutorService}. - */ - public static void cleanup() { - clients.clear(); - clientHealthCheckExecutorService.shutdown(); - } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java index 7333432e..43227475 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java @@ -33,12 +33,7 @@ import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.Collection; import java.util.UUID; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; +import lombok.RequiredArgsConstructor; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyStatus; @@ -46,11 +41,22 @@ import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for PAP component to retrieve the status of deployed * policies. */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class PolicyStatusControllerV1 extends PapRestControllerV1 { private static final String EMPTY_REGEX_ERROR_MESSAGE = "An empty string passed as a regex is not allowed"; private static final String EMPTY_REGEX_WARNING = ". Empty string passed as Regex."; @@ -58,7 +64,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { private static final Logger logger = LoggerFactory.getLogger(PolicyStatusControllerV1.class); - private final PolicyStatusProvider provider = new PolicyStatusProvider(); + private final PolicyStatusProvider provider; /** * Queries status of all deployed policies. If regex is not null or empty, the function will only return @@ -69,8 +75,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @GET - @Path("policies/deployed") + @GetMapping("policies/deployed") @ApiOperation(value = "Queries status of all deployed policies", notes = "Queries status of all deployed policies, returning success and failure counts of the PDPs", responseContainer = "List", response = PolicyStatus.class, @@ -99,9 +104,11 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response queryAllDeployedPolicies( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "Regex for a policy name") @QueryParam("regex") String regex) { + public ResponseEntity queryAllDeployedPolicies( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "Regex for a policy name") @RequestParam(required = false, value = "regex") String regex) { try { final Collection result; if (regex == null) { @@ -115,16 +122,16 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { } catch (PfModelException | PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(e.getErrorResponse().getErrorMessage()).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(e.getErrorResponse().getErrorMessage()); } catch (PatternSyntaxException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.BAD_REQUEST)), requestId) - .entity(e.getMessage()).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.BAD_REQUEST)), requestId) + .body(e.getMessage()); } } - /** * Queries status of specific deployed policies. * @@ -132,8 +139,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @GET - @Path("policies/deployed/{name}") + @GetMapping("policies/deployed/{name}") @ApiOperation(value = "Queries status of specific deployed policies", notes = "Queries status of specific deployed policies, returning success and failure counts of the PDPs", responseContainer = "List", response = PolicyStatus.class, @@ -162,9 +168,11 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response queryDeployedPolicies( - @ApiParam(value = "Policy Id", required = true) @PathParam("name") String name, - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { + public ResponseEntity queryDeployedPolicies( + @ApiParam(value = "Policy Id") @PathVariable("name") String name, + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) { try { Collection result = provider.getStatus(new ToscaConceptIdentifierOptVersion(name, null)); @@ -172,14 +180,14 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { return makeNotFoundResponse(requestId); } else { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(result).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(result); } } catch (PfModelException | PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(e.getErrorResponse().getErrorMessage()).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(e.getErrorResponse().getErrorMessage()); } } @@ -191,8 +199,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @GET - @Path("policies/deployed/{name}/{version}") + @GetMapping("policies/deployed/{name}/{version}") @ApiOperation(value = "Queries status of a specific deployed policy", notes = "Queries status of a specific deployed policy, returning success and failure counts of the PDPs", response = PolicyStatus.class, @@ -221,9 +228,11 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response queryDeployedPolicy(@ApiParam(value = "Policy Id", required = true) @PathParam("name") String name, - @ApiParam(value = "Policy Version", required = true) @PathParam("version") String version, - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { + public ResponseEntity queryDeployedPolicy(@ApiParam(value = "Policy Id") @PathVariable("name") String name, + @ApiParam(value = "Policy Version") @PathVariable("version") String version, + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) { try { Collection result = provider.getStatus(new ToscaConceptIdentifierOptVersion(name, version)); @@ -231,14 +240,15 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { return makeNotFoundResponse(requestId); } else { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(result.iterator().next()).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(result.iterator().next()); } } catch (PfModelException | PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(e.getErrorResponse().getErrorMessage()).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(e.getErrorResponse().getErrorMessage()); } } @@ -250,8 +260,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @GET - @Path("policies/status") + @GetMapping("policies/status") @ApiOperation(value = "Queries status of policies in all PdpGroups", notes = "Queries status of policies in all PdpGroups, " + "returning status of policies in all the PDPs belonging to all PdpGroups", @@ -281,17 +290,20 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response getStatusOfAllPolicies( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { + public ResponseEntity getStatusOfAllPolicies( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) { try { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(provider.getPolicyStatus()).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(provider.getPolicyStatus()); } catch (PfModelException | PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(e.getErrorResponse().getErrorMessage()).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(e.getErrorResponse().getErrorMessage()); } } @@ -305,8 +317,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @GET - @Path("policies/status/{pdpGroupName}") + @GetMapping("policies/status/{pdpGroupName}") @ApiOperation(value = "Queries status of policies in a specific PdpGroup", notes = "Queries status of policies in a specific PdpGroup, " + "returning status of policies in all the PDPs belonging to the PdpGroup", @@ -336,10 +347,12 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response getStatusOfPoliciesByGroup( - @ApiParam(value = "PDP Group Name", required = true) @PathParam("pdpGroupName") String pdpGroupName, - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "Regex for a policy name") @QueryParam("regex") String regex) { + public ResponseEntity getStatusOfPoliciesByGroup( + @ApiParam(value = "PDP Group Name") @PathVariable("pdpGroupName") String pdpGroupName, + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "Regex for a policy name") @RequestParam(required = false, value = "regex") String regex) { try { final Collection result; @@ -354,12 +367,13 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { } catch (PfModelException | PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(e.getErrorResponse().getErrorMessage()).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(e.getErrorResponse().getErrorMessage()); } catch (PatternSyntaxException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.BAD_REQUEST)), requestId) - .entity(e.getMessage()).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.BAD_REQUEST)), requestId) + .body(e.getMessage()); } } @@ -372,8 +386,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @GET - @Path("policies/status/{pdpGroupName}/{policyName}") + @GetMapping("policies/status/{pdpGroupName}/{policyName}") @ApiOperation(value = "Queries status of all versions of a specific policy in a specific PdpGroup", notes = "Queries status of all versions of a specific policy in a specific PdpGroup," + " returning status of all versions of the policy in the PDPs belonging to the PdpGroup", @@ -403,10 +416,12 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response getStatusOfPolicies( - @ApiParam(value = "PDP Group Name", required = true) @PathParam("pdpGroupName") String pdpGroupName, - @ApiParam(value = "Policy Id", required = true) @PathParam("policyName") String policyName, - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { + public ResponseEntity getStatusOfPolicies( + @ApiParam(value = "PDP Group Name") @PathVariable("pdpGroupName") String pdpGroupName, + @ApiParam(value = "Policy Id") @PathVariable("policyName") String policyName, + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) { try { Collection result = @@ -415,14 +430,15 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { return makeNotFoundResponse(requestId); } else { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(result).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(result); } } catch (PfModelException | PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(e.getErrorResponse().getErrorMessage()).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(e.getErrorResponse().getErrorMessage()); } } @@ -437,8 +453,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { * @return a response */ // @formatter:off - @GET - @Path("policies/status/{pdpGroupName}/{policyName}/{policyVersion}") + @GetMapping("policies/status/{pdpGroupName}/{policyName}/{policyVersion}") @ApiOperation(value = "Queries status of a specific version of a specific policy in a specific PdpGroup", notes = "Queries status of a specific version of a specific policy in a specific PdpGroup," + " returning status of the policy in the PDPs belonging to the PdpGroup", @@ -468,11 +483,13 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { }) // @formatter:on - public Response getStatusOfPolicy( - @ApiParam(value = "PDP Group Name", required = true) @PathParam("pdpGroupName") String pdpGroupName, - @ApiParam(value = "Policy Id", required = true) @PathParam("policyName") String policyName, - @ApiParam(value = "Policy Version", required = true) @PathParam("policyVersion") String policyVersion, - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { + public ResponseEntity getStatusOfPolicy( + @ApiParam(value = "PDP Group Name") @PathVariable("pdpGroupName") String pdpGroupName, + @ApiParam(value = "Policy Id") @PathVariable("policyName") String policyName, + @ApiParam(value = "Policy Version") @PathVariable("policyVersion") String policyVersion, + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) { try { Collection result = provider.getPolicyStatus(pdpGroupName, @@ -481,14 +498,15 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { return makeNotFoundResponse(requestId); } else { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(result.iterator().next()).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(result.iterator().next()); } } catch (PfModelException | PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), - requestId).entity(e.getErrorResponse().getErrorMessage()).build(); + return addLoggingHeaders( + addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), + requestId).body(e.getErrorResponse().getErrorMessage()); } } @@ -498,23 +516,22 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { * @param requestId request ID * @return a "not found" response */ - private Response makeNotFoundResponse(final UUID requestId) { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.NOT_FOUND)), requestId) + private ResponseEntity makeNotFoundResponse(final UUID requestId) { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.NOT_FOUND)), requestId) .build(); } - private Response makeRegexNotFoundResponse(UUID requestId) { + private ResponseEntity makeRegexNotFoundResponse(UUID requestId) { logger.warn(GET_DEPLOYMENTS_FAILED + EMPTY_REGEX_WARNING); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.BAD_REQUEST)), - requestId).entity(EMPTY_REGEX_ERROR_MESSAGE).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.BAD_REQUEST)), + requestId).body(EMPTY_REGEX_ERROR_MESSAGE); } - private Response makeListOrNotFoundResponse(UUID requestId, Collection result) { + private ResponseEntity makeListOrNotFoundResponse(UUID requestId, Collection result) { if (result.isEmpty()) { return makeNotFoundResponse(requestId); } else { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(result).build(); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(result); } } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusProvider.java index d8e7e549..dd133a1a 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusProvider.java @@ -35,22 +35,26 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierO import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.notification.DeploymentTracker; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Service; /** * Provider for PAP component to query policy deployment status. */ +@Service public class PolicyStatusProvider { /** * Factory for PAP DAO. */ - private final PolicyModelsProviderFactoryWrapper daoFactory; - + private PolicyModelsProviderFactoryWrapper daoFactory; /** * Constructs the object. Loads all deployed policies into the internal cache. */ - public PolicyStatusProvider() { + @EventListener(ApplicationReadyEvent.class) + public void initialize() { this.daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyUndeployerImpl.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyUndeployerImpl.java index fe584265..ea55f815 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyUndeployerImpl.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyUndeployerImpl.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,12 +43,11 @@ import org.slf4j.LoggerFactory; public class PolicyUndeployerImpl extends ProviderBase implements PolicyUndeployer { private static final Logger logger = LoggerFactory.getLogger(PolicyUndeployerImpl.class); - /** * Constructs the object. */ public PolicyUndeployerImpl() { - super(); + super.initialize(); } @Override diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java b/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java index df5d7bac..ad6ff21e 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java @@ -40,6 +40,8 @@ import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.onap.policy.pap.main.notification.PolicyNotifier; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; /** * Super class of providers that deploy and undeploy PDP groups. The following items must @@ -57,27 +59,28 @@ public abstract class ProviderBase { /** * Lock used when updating PDPs. */ - private final Object updateLock; + private Object updateLock; /** * Used to send UPDATE and STATE-CHANGE requests to the PDPs. */ - private final PdpModifyRequestMap requestMap; + private PdpModifyRequestMap requestMap; /** * Generates policy notifications based on responses from PDPs. */ - private final PolicyNotifier notifier; + private PolicyNotifier notifier; /** * Factory for PAP DAO. */ - private final PolicyModelsProviderFactoryWrapper daoFactory; + private PolicyModelsProviderFactoryWrapper daoFactory; /** - * Constructs the object. + * Initializes the parameters.. */ - protected ProviderBase() { + @EventListener(ApplicationReadyEvent.class) + public void initialize() { this.updateLock = Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class); this.requestMap = Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class); this.daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestControllerV1.java index 718ae574..641e2ba9 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,29 +31,32 @@ import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.time.Instant; +import java.util.List; import java.util.Map; import java.util.UUID; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; +import lombok.RequiredArgsConstructor; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST endpoints for PAP component statistics. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@RestController +@RequestMapping(path = "/policy/pap/v1") +@RequiredArgsConstructor public class StatisticsRestControllerV1 extends PapRestControllerV1 { - private static final Logger LOGGER = LoggerFactory.getLogger(StatisticsRestControllerV1.class); - private static final String GET_STATISTICS_ERR_MSG = "get pdpStatistics failed"; + private final StatisticsRestProvider provider; /** * get statistics of PAP. @@ -60,8 +64,7 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { * * @return a response */ - @GET - @Path("statistics") + @GetMapping("statistics") @ApiOperation(value = "Fetch current statistics", notes = "Returns current statistics of the Policy Administration component", response = StatisticsReport.class, authorizations = @Authorization(value = AUTHORIZATION_TYPE)) @@ -69,11 +72,12 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { @ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE), @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)}) - public Response statistics( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId) { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(new StatisticsRestProvider().fetchCurrentStatistics()) - .build(); + public ResponseEntity statistics( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(provider.fetchCurrentStatistics()); } /** @@ -81,9 +85,9 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { * * * @return a response + * @throws PfModelException the exception */ - @GET - @Path("pdps/statistics") + @GetMapping("pdps/statistics") @ApiOperation(value = "Fetch statistics for all PDP Groups and subgroups in the system", notes = "Returns for all PDP Groups and subgroups statistics of the Policy Administration component", response = Map.class, tags = {"PDP Statistics"}, @@ -110,27 +114,22 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) - public Response pdpStatistics( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "Record Count", required = false) @QueryParam("recordCount") final int recordCount, - @ApiParam(value = "Start time in epoch timestamp", - required = false) @QueryParam("startTime") final Long startTime, - @ApiParam(value = "End time in epoch timestamp", - required = false) @QueryParam("endTime") final Long endTime) { - try { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(new StatisticsRestProvider().fetchDatabaseStatistics(PdpFilterParameters.builder() - .recordNum(recordCount) - .startTime(convertEpochtoInstant(startTime)) - .endTime(convertEpochtoInstant(endTime)) - .build())) - .build(); - } catch (final PfModelException | PfModelRuntimeException exp) { - LOGGER.info(GET_STATISTICS_ERR_MSG, exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), requestId) - .build(); - } + public ResponseEntity>>> pdpStatistics( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "Record Count") @RequestParam( + defaultValue = "10", required = false, + value = "recordCount") final int recordCount, + @ApiParam(value = "Start time in epoch timestamp") @RequestParam( + required = false, + value = "startTime") final Long startTime, + @ApiParam(value = "End time in epoch timestamp") @RequestParam( + required = false, + value = "endTime") final Long endTime) throws PfModelException { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(provider.fetchDatabaseStatistics(PdpFilterParameters.builder().recordNum(recordCount) + .startTime(convertEpochtoInstant(startTime)).endTime(convertEpochtoInstant(endTime)).build())); } /** @@ -138,9 +137,9 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { * * @param groupName name of the PDP group * @return a response + * @throws PfModelException the exception */ - @GET - @Path("pdps/statistics/{group}") + @GetMapping("pdps/statistics/{group}") @ApiOperation(value = "Fetch current statistics for given PDP Group", notes = "Returns statistics for given PDP Group of the Policy Administration component", response = Map.class, tags = {"PDP Statistics"}, @@ -166,29 +165,23 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) - public Response pdpGroupStatistics( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "PDP Group Name", required = true) @PathParam("group") final String groupName, - @ApiParam(value = "Record Count", required = false) @QueryParam("recordCount") final int recordCount, - @ApiParam(value = "Start time in epoch timestamp", - required = false) @QueryParam("startTime") final Long startTime, - @ApiParam(value = "End time in epoch timestamp", - required = false) @QueryParam("endTime") final Long endTime) { - try { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(new StatisticsRestProvider().fetchDatabaseStatistics(PdpFilterParameters.builder() - .group(groupName) - .recordNum(recordCount) - .startTime(convertEpochtoInstant(startTime)) - .endTime(convertEpochtoInstant(endTime)) - .build())) - .build(); - } catch (final PfModelException | PfModelRuntimeException exp) { - LOGGER.info(GET_STATISTICS_ERR_MSG, exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), requestId) - .build(); - } + public ResponseEntity>>> pdpGroupStatistics( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "PDP Group Name") @PathVariable("group") final String groupName, + @ApiParam(value = "Record Count") @RequestParam( + defaultValue = "10", required = false, + value = "recordCount") final int recordCount, + @ApiParam(value = "Start time in epoch timestamp") @RequestParam( + required = false, + value = "startTime") final Long startTime, + @ApiParam(value = "End time in epoch timestamp") @RequestParam( + required = false, + value = "endTime") final Long endTime) throws PfModelException { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(provider.fetchDatabaseStatistics(PdpFilterParameters.builder().group(groupName).recordNum(recordCount) + .startTime(convertEpochtoInstant(startTime)).endTime(convertEpochtoInstant(endTime)).build())); } /** @@ -197,9 +190,9 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { * @param groupName name of the PDP group * @param subType type of the sub PDP group * @return a response + * @throws PfModelException the exception */ - @GET - @Path("pdps/statistics/{group}/{type}") + @GetMapping("pdps/statistics/{group}/{type}") @ApiOperation(value = "Fetch statistics for the specified subgroup", notes = "Returns statistics for the specified subgroup of the Policy Administration component", response = Map.class, tags = {"PDP Statistics"}, @@ -225,31 +218,25 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) - public Response pdpSubGroupStatistics( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "PDP Group Name", required = true) @PathParam("group") final String groupName, - @ApiParam(value = "PDP SubGroup type", required = true) @PathParam("type") final String subType, - @ApiParam(value = "Record Count", required = false) @QueryParam("recordCount") final int recordCount, - @ApiParam(value = "Start time in epoch timestamp", - required = false) @QueryParam("startTime") final Long startTime, - @ApiParam(value = "End time in epoch timestamp", - required = false) @QueryParam("endTime") final Long endTime) { - try { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(new StatisticsRestProvider().fetchDatabaseStatistics(PdpFilterParameters.builder() - .group(groupName) - .subGroup(subType) - .recordNum(recordCount) - .startTime(convertEpochtoInstant(startTime)) - .endTime(convertEpochtoInstant(endTime)) - .build())) - .build(); - } catch (final PfModelException | PfModelRuntimeException exp) { - LOGGER.info(GET_STATISTICS_ERR_MSG, exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), requestId) - .build(); - } + public ResponseEntity>>> pdpSubGroupStatistics( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "PDP Group Name") @PathVariable("group") final String groupName, + @ApiParam(value = "PDP SubGroup type") @PathVariable("type") final String subType, + @ApiParam(value = "Record Count") @RequestParam( + defaultValue = "10", required = false, + value = "recordCount") final int recordCount, + @ApiParam(value = "Start time in epoch timestamp") @RequestParam( + required = false, + value = "startTime") final Long startTime, + @ApiParam(value = "End time in epoch timestamp") @RequestParam( + required = false, + value = "endTime") final Long endTime) throws PfModelException { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(provider.fetchDatabaseStatistics( + PdpFilterParameters.builder().group(groupName).subGroup(subType).recordNum(recordCount) + .startTime(convertEpochtoInstant(startTime)).endTime(convertEpochtoInstant(endTime)).build())); } /** @@ -260,9 +247,9 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { * @param pdpName the name of the PDP * @param recordCount the count of the query response, optional, default return all statistics stored * @return a response + * @throws PfModelException the exception */ - @GET - @Path("pdps/statistics/{group}/{type}/{pdp}") + @GetMapping("pdps/statistics/{group}/{type}/{pdp}") @ApiOperation(value = "Fetch statistics for the specified pdp", notes = "Returns statistics for the specified pdp of the Policy Administration component", response = Map.class, @@ -289,34 +276,26 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE) }) - public Response pdpInstanceStatistics( - @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) final UUID requestId, - @ApiParam(value = "PDP Group Name", required = true) @PathParam("group") final String groupName, - @ApiParam(value = "PDP SubGroup type", required = true) @PathParam("type") final String subType, - @ApiParam(value = "PDP Instance name", required = true) @PathParam("pdp") final String pdpName, - @ApiParam(value = "Record Count", required = false) @QueryParam("recordCount") final int recordCount, - @ApiParam(value = "Start time in epoch timestamp", - required = false) @QueryParam("startTime") final Long startTime, - @ApiParam(value = "End time in epoch timestamp", - required = false) @QueryParam("endTime") final Long endTime) { - try { - return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) - .entity(new StatisticsRestProvider().fetchDatabaseStatistics( - PdpFilterParameters.builder() - .group(groupName) - .subGroup(subType) - .name(pdpName) - .recordNum(recordCount) - .startTime(convertEpochtoInstant(startTime)) - .endTime(convertEpochtoInstant(endTime)) - .build())) - .build(); - } catch (final PfModelException | PfModelRuntimeException exp) { - LOGGER.info(GET_STATISTICS_ERR_MSG, exp); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(exp.getErrorResponse().getResponseCode())), requestId) - .build(); - } + public ResponseEntity>>> pdpInstanceStatistics( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId, + @ApiParam(value = "PDP Group Name") @PathVariable("group") final String groupName, + @ApiParam(value = "PDP SubGroup type") @PathVariable("type") final String subType, + @ApiParam(value = "PDP Instance name") @PathVariable("pdp") final String pdpName, + @ApiParam(value = "Record Count") @RequestParam( + defaultValue = "10", required = false, + value = "recordCount") final int recordCount, + @ApiParam(value = "Start time in epoch timestamp") @RequestParam( + required = false, + value = "startTime") final Long startTime, + @ApiParam(value = "End time in epoch timestamp") @RequestParam( + required = false, + value = "endTime") final Long endTime) throws PfModelException { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(provider.fetchDatabaseStatistics( + PdpFilterParameters.builder().group(groupName).subGroup(subType).name(pdpName).recordNum(recordCount) + .startTime(convertEpochtoInstant(startTime)).endTime(convertEpochtoInstant(endTime)).build())); } private Instant convertEpochtoInstant(Long epochSecond) { diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestProvider.java index d2771d67..51f10fef 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestProvider.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2020-2021 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,12 +36,14 @@ import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.startstop.PapActivator; +import org.springframework.stereotype.Service; /** * Class to fetch statistics of pap component. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@Service public class StatisticsRestProvider { private static final String GET_STATISTICS_ERR_MSG = "database query failed"; diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java b/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java deleted file mode 100644 index 5918ed12..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java +++ /dev/null @@ -1,161 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.startstop; - -import java.util.Arrays; -import org.onap.policy.common.utils.resources.MessageConstants; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyPapRuntimeException; -import org.onap.policy.pap.main.parameters.PapParameterGroup; -import org.onap.policy.pap.main.parameters.PapParameterHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class initiates ONAP Policy Framework PAP component. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class Main { - - private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); - - private PapActivator activator; - private PapParameterGroup parameterGroup; - - /** - * Instantiates the policy pap service. - * - * @param args the command line arguments - */ - public Main(final String[] args) { - final var argumentString = Arrays.toString(args); - LOGGER.info("Starting policy pap service with arguments - {}", argumentString); - - // Check the arguments - final var arguments = new PapCommandLineArguments(); - try { - // The arguments return a string if there is a message to print and we should exit - final String argumentMessage = arguments.parse(args); - if (argumentMessage != null) { - LOGGER.info(argumentMessage); - return; - } - // Validate that the arguments are sane - arguments.validate(); - - // Read the parameters - parameterGroup = new PapParameterHandler().getParameters(arguments); - - // Initialize database - new PapDatabaseInitializer().initializePapDatabase( - parameterGroup.getDatabaseProviderParameters(), - arguments.getPdpGroupsConfiguration()); - - // Now, create the activator for the policy pap service - activator = new PapActivator(parameterGroup); - Registry.register(PapConstants.REG_PAP_ACTIVATOR, activator); - - // Start the activator - activator.start(); - } catch (Exception exp) { // NOSONAR - /* - * Disabled sonar on the above line, because we want to capture the stack - * trace via the logger while still reporting the exception message on stdout - * when the JVM exits. - */ - LOGGER.error("failed to start Main", exp); - if (null != activator) { - Registry.unregister(PapConstants.REG_PAP_ACTIVATOR); - } - throw new PolicyPapRuntimeException( - String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_PAP), exp); - } - - // Add a shutdown hook to shut everything down in an orderly manner - Runtime.getRuntime().addShutdownHook(new PolicyPapShutdownHookClass()); - var successMsg = String.format(MessageConstants.START_SUCCESS_MSG, MessageConstants.POLICY_PAP); - LOGGER.info(successMsg); - } - - /** - * Get the parameters specified in JSON. - * - * @return the parameters - */ - public PapParameterGroup getParameters() { - return parameterGroup; - } - - /** - * Shut down Execution. - * - */ - public void shutdown() { - // clear the parameterGroup variable - parameterGroup = null; - - // clear the pap activator - if (activator != null) { - activator.stop(); - } - } - - /** - * The Class PolicyPapShutdownHookClass terminates the policy pap service when its run method is called. - */ - private class PolicyPapShutdownHookClass extends Thread { - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - if (!activator.isAlive()) { - return; - } - - try { - // Shutdown the policy pap service and wait for everything to stop - activator.stop(); - } catch (final RuntimeException e) { - LOGGER.warn("error occurred during shut down of the policy pap service", e); - } - } - } - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(final String[] args) { // NOSONAR - /* - * NOTE: arguments are validated by the constructor, thus sonar is disabled. - */ - - new Main(args); - } -} diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java index ad78fc7c..94943706 100644 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java @@ -30,8 +30,6 @@ import java.util.concurrent.atomic.AtomicReference; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.event.comm.TopicListener; import org.onap.policy.common.endpoints.event.comm.TopicSource; -import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; -import org.onap.policy.common.endpoints.http.server.RestServer; import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher; import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher; import org.onap.policy.common.parameters.ParameterService; @@ -51,21 +49,12 @@ import org.onap.policy.pap.main.comm.TimerManager; import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams; -import org.onap.policy.pap.main.rest.HealthCheckRestControllerV1; -import org.onap.policy.pap.main.rest.PapAafFilter; import org.onap.policy.pap.main.rest.PapStatisticsManager; -import org.onap.policy.pap.main.rest.PdpGroupCreateOrUpdateControllerV1; -import org.onap.policy.pap.main.rest.PdpGroupDeleteControllerV1; -import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1; -import org.onap.policy.pap.main.rest.PdpGroupHealthCheckControllerV1; -import org.onap.policy.pap.main.rest.PdpGroupQueryControllerV1; -import org.onap.policy.pap.main.rest.PdpGroupStateChangeControllerV1; -import org.onap.policy.pap.main.rest.PolicyAuditControllerV1; -import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckControllerV1; -import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckProvider; -import org.onap.policy.pap.main.rest.PolicyStatusControllerV1; import org.onap.policy.pap.main.rest.PolicyUndeployerImpl; -import org.onap.policy.pap.main.rest.StatisticsRestControllerV1; +import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; /** * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners & @@ -73,6 +62,7 @@ import org.onap.policy.pap.main.rest.StatisticsRestControllerV1; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@Component public class PapActivator extends ServiceManagerContainer { private static final String[] MSG_TYPE_NAMES = { "messageName" }; private static final String[] REQ_ID_NAMES = { "response", "responseTo" }; @@ -82,7 +72,7 @@ public class PapActivator extends ServiceManagerContainer { */ private static final int MAX_MISSED_HEARTBEATS = 3; - private final PapParameterGroup papParameterGroup; + private PapParameterGroup papParameterGroup; /** * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to @@ -108,13 +98,12 @@ public class PapActivator extends ServiceManagerContainer { * * @param papParameterGroup the parameters for the pap service */ - public PapActivator(final PapParameterGroup papParameterGroup) { + public PapActivator(PapParameterGroup papParameterGroup) { super("Policy PAP"); - + this.papParameterGroup = papParameterGroup; TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup()); try { - this.papParameterGroup = papParameterGroup; this.responseMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES); this.heartbeatMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES); this.responseReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES); @@ -126,7 +115,6 @@ public class PapActivator extends ServiceManagerContainer { throw new PolicyPapRuntimeException(e); } - papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName()); final var pdpUpdateLock = new Object(); final var pdpParams = papParameterGroup.getPdpParameters(); @@ -137,7 +125,6 @@ public class PapActivator extends ServiceManagerContainer { final AtomicReference pdpExpirationTimer = new AtomicReference<>(); final AtomicReference daoFactory = new AtomicReference<>(); final AtomicReference requestMap = new AtomicReference<>(); - final AtomicReference restServer = new AtomicReference<>(); final AtomicReference notifier = new AtomicReference<>(); // @formatter:off @@ -182,6 +169,10 @@ public class PapActivator extends ServiceManagerContainer { () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()), () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER)); + addAction("PAP Activator", + () -> Registry.register(PapConstants.REG_PAP_ACTIVATOR, this), + () -> Registry.unregister(PapConstants.REG_PAP_ACTIVATOR)); + addAction("PDP publisher", () -> { pdpPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_PDP_PAP)); @@ -253,30 +244,6 @@ public class PapActivator extends ServiceManagerContainer { }, () -> pdpExpirationTimer.get().shutdown()); - addAction("PAP client executor", - () -> - PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup, - HttpClientFactoryInstance.getClientFactory()), - PolicyComponentsHealthCheckProvider::cleanup); - - addAction("REST server", - () -> { - var server = new RestServer(papParameterGroup.getRestServerParameters(), PapAafFilter.class, - HealthCheckRestControllerV1.class, - StatisticsRestControllerV1.class, - PdpGroupCreateOrUpdateControllerV1.class, - PdpGroupDeployControllerV1.class, - PdpGroupDeleteControllerV1.class, - PdpGroupStateChangeControllerV1.class, - PdpGroupQueryControllerV1.class, - PdpGroupHealthCheckControllerV1.class, - PolicyStatusControllerV1.class, - PolicyComponentsHealthCheckControllerV1.class, - PolicyAuditControllerV1.class); - restServer.set(server); - restServer.get().start(); - }, - () -> restServer.get().stop()); // @formatter:on } @@ -322,4 +289,28 @@ public class PapActivator extends ServiceManagerContainer { source.unregister(dispatcher); } } + + /** + * Handle ContextRefreshEvent. + * + * @param ctxRefreshedEvent the ContextRefreshedEvent + */ + @EventListener + public void handleContextRefreshEvent(ContextRefreshedEvent ctxRefreshedEvent) { + if (!isAlive()) { + start(); + } + } + + /** + * Handle ContextClosedEvent. + * + * @param ctxClosedEvent the ContextClosedEvent + */ + @EventListener + public void handleContextClosedEvent(ContextClosedEvent ctxClosedEvent) { + if (isAlive()) { + stop(); + } + } } diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java deleted file mode 100644 index afc8fbca..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. - * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.startstop; - -import org.apache.commons.cli.Option; -import org.onap.policy.common.utils.cmd.CommandLineArgumentsHandler; -import org.onap.policy.common.utils.cmd.CommandLineException; -import org.onap.policy.common.utils.resources.MessageConstants; -import org.onap.policy.pap.main.PolicyPapRuntimeException; - -/** - * This class reads and handles command line parameters for the policy pap service. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class PapCommandLineArguments extends CommandLineArgumentsHandler { - - protected static final String GROUP_FILE_OPTION = "g"; - protected static final String GROUP_FILE_LONG_OPTION = "groups-file"; - public static final String GROUP_FILE_ARG_NAME = "GROUP_FILE"; - - protected static final String DEFAULT_GROUP_RESOURCE = "PapDb.json"; - - /** - * Construct the options for the CLI editor. - */ - public PapCommandLineArguments() { - super(Main.class.getName(), MessageConstants.POLICY_PAP, customOptionG()); - } - - private static Option customOptionG() { - return Option.builder(GROUP_FILE_OPTION).longOpt(GROUP_FILE_LONG_OPTION) - .desc("the full path to the groups file to use, " - + "the groups file contains the group configuration added to the DB") - .hasArg().argName(GROUP_FILE_ARG_NAME).required(false).type(String.class).build(); - } - - protected String getPdpGroupsConfiguration() { - return this.getCommandLine() - .getOptionValue(GROUP_FILE_OPTION, DEFAULT_GROUP_RESOURCE); - } - - @Override - public void validate() throws CommandLineException { - super.validate(); - String groupConfig = getPdpGroupsConfiguration(); - if (!groupConfig.equals(DEFAULT_GROUP_RESOURCE)) { - validateReadableFile(MessageConstants.POLICY_PAP, groupConfig); - } - } - - /** - * Construct the options for the CLI editor and parse in the given arguments. - * - * @param args The command line arguments - */ - public PapCommandLineArguments(final String[] args) { - this(); - - try { - parse(args); - } catch (final CommandLineException e) { - throw new PolicyPapRuntimeException("parse error on policy pap parameters", e); - } - } -} diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapDatabaseInitializer.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapDatabaseInitializer.java index d180c934..617cdf36 100644 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/PapDatabaseInitializer.java +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapDatabaseInitializer.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +23,7 @@ package org.onap.policy.pap.main.startstop; import java.util.List; +import javax.annotation.PostConstruct; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -32,14 +34,21 @@ import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; /** * This class creates initial PdpGroup/SubGroup in the database. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@Component +@ConditionalOnProperty(value = "db.initialize", havingValue = "true", matchIfMissing = true) public class PapDatabaseInitializer { private static final Logger LOGGER = LoggerFactory.getLogger(PapDatabaseInitializer.class); @@ -47,6 +56,12 @@ public class PapDatabaseInitializer { private final StandardCoder standardCoder; private final PolicyModelsProviderFactory factory; + @Autowired + private PapParameterGroup papParameterGroup; + + @Value("${group-config-file:PapDb.json}") + private String groupConfigFile; + /** * Constructs the object. */ @@ -59,9 +74,10 @@ public class PapDatabaseInitializer { * Initializes database with group information. * * @param policyModelsProviderParameters the database parameters + * @param groupsJson the group file path * @throws PolicyPapException in case of errors. */ - public void initializePapDatabase( + private void initializePapDatabase( final PolicyModelsProviderParameters policyModelsProviderParameters, String groupsJson) throws PolicyPapException { @@ -86,4 +102,12 @@ public class PapDatabaseInitializer { throw new PolicyPapException(exp); } } + + /** + * Initializes database with group information. + */ + @PostConstruct + public void loadData() throws PolicyPapException { + initializePapDatabase(papParameterGroup.getDatabaseProviderParameters(), groupConfigFile); + } } diff --git a/main/src/main/resources/application.yaml b/main/src/main/resources/application.yaml new file mode 100644 index 00000000..f37cc762 --- /dev/null +++ b/main/src/main/resources/application.yaml @@ -0,0 +1,82 @@ +spring: + security: + user: + name: policyadmin + password: zb!XztG34 + http: + converters: + preferred-json-mapper: gson + +server: + port: 6969 + +pap: + name: PapGroup + pdpParameters: + heartBeatMs: 120000 + updateParameters: + maxRetryCount: 1 + maxWaitMs: 30000 + stateChangeParameters: + maxRetryCount: 1 + maxWaitMs: 30000 + databaseProviderParameters: + name: PolicyProviderParameterGroup + implementation: org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl + databaseDriver: org.mariadb.jdbc.Driver + databaseUrl: jdbc:mariadb://mariadb:3306/policyadmin + databaseUser: policy_user + databasePassword: policy_user + persistenceUnit: PolicyMariaDb + savePdpStatisticsInDb: true + topicParameterGroup: + topicSources: + - topic: POLICY-PDP-PAP + servers: + - message-router + topicCommInfrastructure: dmaap + fetchTimeout: 15000 + - topic: POLICY-HEARTBEAT + effectiveTopic: POLICY-PDP-PAP + consumerGroup: policy-pap + servers: + - message-router + topicCommInfrastructure: dmaap + fetchTimeout: 15000 + topicSinks: + - topic: POLICY-PDP-PAP + servers: + - message-router + topicCommInfrastructure: dmaap + - topic: POLICY-NOTIFICATION + servers: + - message-router + topicCommInfrastructure: dmaap + healthCheckRestClientParameters: + - clientName: api + hostname: policy-api + port: 6969 + userName: policyadmin + password: zb!XztG34 + useHttps: true + basePath: policy/api/v1/healthcheck + - clientName: distribution + hostname: policy-distribution + port: 6969 + userName: healthcheck + password: zb!XztG34 + useHttps: true + basePath: healthcheck + - clientName: dmaap + hostname: message-router + port: 3905 + useHttps: true + basePath: topics + +management: + endpoints: + web: + base-path: / + exposure: + include: health, metrics, prometheus + path-mapping.prometheus: metrics diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java index 2c0479b1..51ced7bd 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PublisherTest.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,9 +45,8 @@ import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; -import org.onap.policy.pap.main.parameters.PapParameterHandler; -import org.onap.policy.pap.main.startstop.PapCommandLineArguments; public class PublisherTest extends Threaded { @@ -85,9 +85,7 @@ public class PublisherTest extends Threaded { */ @BeforeClass public static void setUpBeforeClass() throws Exception { - final String[] papConfigParameters = {"-c", "parameters/PapConfigParameters.json"}; - final PapCommandLineArguments arguments = new PapCommandLineArguments(papConfigParameters); - final PapParameterGroup parameterGroup = new PapParameterHandler().getParameters(arguments); + final PapParameterGroup parameterGroup = new CommonTestData().getPapParameterGroup(6969); TopicEndpointManager.getManager().shutdown(); TopicEndpointManager.getManager().addTopics(parameterGroup.getTopicParameterGroup()); diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java index 14000e60..34d72203 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +42,7 @@ public class CommonTestData { private static final Coder coder = new StandardCoder(); - private static int dbNum = 0; + public static int dbNum = 0; public static void newDb() { ++dbNum; diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java index 8962f45b..926a1f49 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +28,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.onap.policy.common.endpoints.parameters.RestServerParameters; import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.Coder; @@ -52,17 +52,10 @@ public class TestPapParameterGroup { @Test public void testPapParameterGroup() { final PapParameterGroup papParameters = commonTestData.getPapParameterGroup(1); - final RestServerParameters restServerParameters = papParameters.getRestServerParameters(); final TopicParameterGroup topicParameterGroup = papParameters.getTopicParameterGroup(); final ValidationResult validationResult = papParameters.validate(); assertTrue(validationResult.isValid()); assertEquals(CommonTestData.PAP_GROUP_NAME, papParameters.getName()); - assertEquals(restServerParameters.getHost(), papParameters.getRestServerParameters().getHost()); - assertEquals(restServerParameters.getPort(), papParameters.getRestServerParameters().getPort()); - assertEquals(restServerParameters.getUserName(), papParameters.getRestServerParameters().getUserName()); - assertEquals(restServerParameters.getPassword(), papParameters.getRestServerParameters().getPassword()); - assertTrue(papParameters.getRestServerParameters().isHttps()); - assertFalse(papParameters.getRestServerParameters().isAaf()); assertEquals(topicParameterGroup.getTopicSinks(), papParameters.getTopicParameterGroup().getTopicSinks()); assertEquals(topicParameterGroup.getTopicSources(), papParameters.getTopicParameterGroup().getTopicSources()); } @@ -96,14 +89,4 @@ public class TestPapParameterGroup { assertEquals("PapNewGroup", papParameters.getName()); } - @Test - public void testApiParameterGroup_EmptyRestServerParameters() throws Exception { - String json = commonTestData.getPapParameterGroupAsString(1); - json = commonTestData.nullifyField(json, "restServerParameters"); - final PapParameterGroup papParameters = commonTestData.getPapParameterGroup(0); - final ValidationResult validationResult = papParameters.validate(); - assertFalse(validationResult.isValid()); - assertThat(validationResult.getResult()) - .contains("\"RestServerParameters\" INVALID, item has status INVALID"); - } } diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java deleted file mode 100644 index 6b6431fa..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.parameters; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.FileNotFoundException; -import org.junit.Test; -import org.onap.policy.common.utils.cmd.CommandLineException; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.pap.main.PolicyPapException; -import org.onap.policy.pap.main.startstop.PapCommandLineArguments; - -/** - * Class to perform unit test of {@link PapParameterHandler}. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class TestPapParameterHandler { - - @Test - public void testParameterHandlerNoParameterFile() throws PolicyPapException, CommandLineException { - final String[] noArgumentString = { "-c", "parameters/NoParameterFile.json" }; - - final PapCommandLineArguments noArguments = new PapCommandLineArguments(); - noArguments.parse(noArgumentString); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(noArguments)) - .hasCauseInstanceOf(CoderException.class) - .hasRootCauseInstanceOf(FileNotFoundException.class); - } - - @Test - public void testParameterHandlerEmptyParameters() throws PolicyPapException, CommandLineException { - final String[] emptyArgumentString = { "-c", "parameters/EmptyParameters.json" }; - - final PapCommandLineArguments emptyArguments = new PapCommandLineArguments(); - emptyArguments.parse(emptyArgumentString); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(emptyArguments)) - .hasMessageContaining("no parameters found in \"parameters/EmptyParameters.json\""); - } - - @Test - public void testParameterHandlerInvalidParameters() throws PolicyPapException, CommandLineException { - final String[] invalidArgumentString = { "-c", "parameters/InvalidParameters.json" }; - - final PapCommandLineArguments invalidArguments = new PapCommandLineArguments(); - invalidArguments.parse(invalidArgumentString); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(invalidArguments)) - .hasMessageStartingWith("error reading parameters from \"parameters/InvalidParameters.json\"") - .hasCauseInstanceOf(CoderException.class); - } - - @Test - public void testParameterHandlerNoParameters() throws PolicyPapException, CommandLineException { - final String[] noArgumentString = { "-c", "parameters/NoParameters.json" }; - - final PapCommandLineArguments noArguments = new PapCommandLineArguments(); - noArguments.parse(noArgumentString); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(noArguments)).hasMessageContaining("is null"); - } - - @Test - public void testParameterHandlerMinumumParameters() throws PolicyPapException, CommandLineException { - final String[] minArgumentString = { "-c", "parameters/MinimumParameters.json" }; - - final PapCommandLineArguments minArguments = new PapCommandLineArguments(); - minArguments.parse(minArgumentString); - - final PapParameterGroup parGroup = new PapParameterHandler().getParameters(minArguments); - assertEquals(CommonTestData.PAP_GROUP_NAME, parGroup.getName()); - } - - @Test - public void testPapParameterGroup() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters.json" }; - - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - arguments.parse(papConfigParameters); - - final PapParameterGroup parGroup = new PapParameterHandler().getParameters(arguments); - assertTrue(arguments.checkSetConfigurationFilePath()); - assertEquals(CommonTestData.PAP_GROUP_NAME, parGroup.getName()); - } - - @Test - public void testPapParameterGroup_InvalidName() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters_InvalidName.json" }; - - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - arguments.parse(papConfigParameters); - - assertThatThrownBy(() -> new PapParameterHandler().getParameters(arguments)) - .hasMessageContaining("\"name\" value \" \" INVALID, is blank"); - } - - @Test - public void testPapVersion() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-v" }; - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - final String version = arguments.parse(papConfigParameters); - assertTrue(version.startsWith("ONAP Policy Framework PAP Service")); - } - - @Test - public void testPapHelp() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-h" }; - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - final String help = arguments.parse(papConfigParameters); - assertTrue(help.startsWith("usage:")); - } - - @Test - public void testPapInvalidOption() throws PolicyPapException, CommandLineException { - final String[] papConfigParameters = { "-d" }; - final PapCommandLineArguments arguments = new PapCommandLineArguments(); - assertThatThrownBy(() -> arguments.parse(papConfigParameters)) - .hasMessageStartingWith("invalid command line arguments specified"); - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java index 98a24a62..9673c295 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +29,6 @@ import java.io.File; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; -import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import javax.net.ssl.SSLContext; @@ -41,35 +41,41 @@ import javax.ws.rs.core.Response; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; +import org.junit.runner.RunWith; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; import org.onap.policy.common.gson.GsonMessageBodyHandler; import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.common.utils.security.SelfSignedKeyStore; import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.PolicyPapApplication; import org.onap.policy.pap.main.parameters.CommonTestData; -import org.onap.policy.pap.main.startstop.Main; import org.onap.policy.pap.main.startstop.PapActivator; import org.powermock.reflect.Whitebox; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.junit4.SpringRunner; /** * Class to perform unit test of {@link PapRestControllerV1}. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class CommonPapRestServer { +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PolicyPapApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = {"db.initialize=false"}) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +public abstract class CommonPapRestServer { protected static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParams.json"; - private static final Logger LOGGER = LoggerFactory.getLogger(CommonPapRestServer.class); - public static final String NOT_ALIVE = "not alive"; public static final String ALIVE = "alive"; public static final String SELF = NetworkUtil.getHostname(); @@ -77,59 +83,38 @@ public class CommonPapRestServer { public static final String ENDPOINT_PREFIX = "policy/pap/v1/"; private static SelfSignedKeyStore keystore; - private static int port; - protected static String httpsPrefix; - - private static Main main; private boolean activatorWasAlive; + protected String httpsPrefix; + + @LocalServerPort + private int port; + + @Autowired + private PapActivator papActivator; /** - * Allocates a port for the server, writes a config file, and then starts Main. + * Allocates a new db url, writes a config file. * * @throws Exception if an error occurs */ @BeforeClass public static void setUpBeforeClass() throws Exception { - setUpBeforeClass(true); - } - - /** - * Allocates a port for the server, writes a config file, and then starts Main, if - * specified. - * - * @param shouldStart {@code true} if Main should be started, {@code false} otherwise - * @throws Exception if an error occurs - */ - public static void setUpBeforeClass(boolean shouldStart) throws Exception { keystore = new SelfSignedKeyStore(); - port = NetworkUtil.allocPort(); - - httpsPrefix = "https://localhost:" + port + "/"; - + CommonTestData.newDb(); makeConfigFile(); HttpServletServerFactoryInstance.getServerFactory().destroy(); TopicEndpointManager.getManager().shutdown(); - - CommonTestData.newDb(); - - if (shouldStart) { - startMain(); - } + Registry.newRegistry(); } - /** - * Stops Main. - */ - @AfterClass - public static void teardownAfterClass() { - try { - stopMain(); - - } catch (PolicyPapException exp) { - LOGGER.error("cannot stop main", exp); - } + @DynamicPropertySource + static void registerPgProperties(DynamicPropertyRegistry registry) { + registry.add("pap.databaseProviderParameters.databaseUrl", () -> "jdbc:h2:mem:testdb" + CommonTestData.dbNum); + registry.add("server.ssl.enabled", () -> "true"); + registry.add("server.ssl.key-store", () -> keystore.getKeystoreName()); + registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD); } /** @@ -139,12 +124,8 @@ public class CommonPapRestServer { */ @Before public void setUp() throws Exception { - // restart, if not currently running - if (main == null) { - startMain(); - } - - activatorWasAlive = Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class).isAlive(); + httpsPrefix = "https://localhost:" + port + "/"; + activatorWasAlive = papActivator.isAlive(); } /** @@ -162,10 +143,9 @@ public class CommonPapRestServer { * @throws Exception if an error occurs */ protected void testSwagger(final String endpoint) throws Exception { - final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml", true); + final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "v2/api-docs", true); final String resp = invocationBuilder.get(String.class); - - assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":")); + assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint)); } /** @@ -174,7 +154,7 @@ public class CommonPapRestServer { * @throws Exception if an error occurs */ private static void makeConfigFile() throws Exception { - String json = new CommonTestData().getPapParameterGroupAsString(port); + String json = new CommonTestData().getPapParameterGroupAsString(6969); File file = new File(CONFIG_FILE); file.deleteOnExit(); @@ -184,47 +164,6 @@ public class CommonPapRestServer { } } - /** - * Starts the "Main". - * - * @throws Exception if an error occurs - */ - protected static void startMain() throws Exception { - Registry.newRegistry(); - - // make sure port is available - if (NetworkUtil.isTcpPortOpen("localhost", port, 1, 1L)) { - throw new IllegalStateException("port " + port + " is still in use"); - } - - final Properties systemProps = System.getProperties(); - systemProps.put("javax.net.ssl.keyStore", keystore.getKeystoreName()); - systemProps.put("javax.net.ssl.keyStorePassword", SelfSignedKeyStore.KEYSTORE_PASSWORD); - System.setProperties(systemProps); - - final String[] papConfigParameters = { "-c", CONFIG_FILE }; - - main = new Main(papConfigParameters); - - if (!NetworkUtil.isTcpPortOpen("localhost", port, 6, 10000L)) { - throw new IllegalStateException("server is not listening on port " + port); - } - } - - /** - * Stops the "Main". - * - * @throws PolicyPapException if an error occurs - */ - private static void stopMain() throws PolicyPapException { - if (main != null) { - Main main2 = main; - main = null; - - main2.shutdown(); - } - } - /** * Mark the activator as dead, but leave its REST server running. */ @@ -233,8 +172,7 @@ public class CommonPapRestServer { } private void markActivator(boolean wasAlive) { - Object manager = Whitebox.getInternalState(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class), - "serviceManager"); + Object manager = Whitebox.getInternalState(papActivator, "serviceManager"); AtomicBoolean running = Whitebox.getInternalState(manager, "running"); running.set(wasAlive); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java index aafcd40f..f8e47ef4 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,15 +25,8 @@ package org.onap.policy.pap.main.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import java.security.Principal; import java.util.UUID; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.SecurityContext; import org.junit.After; import org.junit.Before; @@ -40,7 +34,8 @@ import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.internal.stubbing.answers.Returns; +import org.springframework.http.ResponseEntity; +import org.springframework.http.ResponseEntity.BodyBuilder; public class PapRestControllerV1Test { @@ -51,11 +46,11 @@ public class PapRestControllerV1Test { PapRestControllerV1 mockController; private AutoCloseable closeable; - private ResponseBuilder bldr; + private BodyBuilder bldr; @Before public void setUp() { - bldr = Response.status(Response.Status.OK); + bldr = ResponseEntity.ok(); closeable = MockitoAnnotations.openMocks(this); } @@ -64,42 +59,29 @@ public class PapRestControllerV1Test { closeable.close(); } - @Test - public void testProduces() { - Produces annotation = PapRestControllerV1.class.getAnnotation(Produces.class); - assertNotNull(annotation); - assertThat(annotation.value()).contains(MediaType.APPLICATION_JSON) - .contains(PapRestControllerV1.APPLICATION_YAML); - } - @Test public void testAddVersionControlHeaders() { - Response resp = mockController.addVersionControlHeaders(bldr).build(); - assertEquals("0", resp.getHeaderString(PapRestControllerV1.VERSION_MINOR_NAME)); - assertEquals("0", resp.getHeaderString(PapRestControllerV1.VERSION_PATCH_NAME)); - assertEquals("1.0.0", resp.getHeaderString(PapRestControllerV1.VERSION_LATEST_NAME)); + ResponseEntity resp = mockController.addVersionControlHeaders(bldr).build(); + assertEquals("0", resp.getHeaders().get(PapRestControllerV1.VERSION_MINOR_NAME).get(0)); + assertEquals("0", resp.getHeaders().get(PapRestControllerV1.VERSION_PATCH_NAME).get(0)); + assertEquals("1.0.0", resp.getHeaders().get(PapRestControllerV1.VERSION_LATEST_NAME).get(0)); } @Test public void testAddLoggingHeaders_Null() { - Response resp = mockController.addLoggingHeaders(bldr, null).build(); - assertNotNull(resp.getHeaderString(PapRestControllerV1.REQUEST_ID_NAME)); + ResponseEntity resp = mockController.addLoggingHeaders(bldr, null).build(); + assertNotNull(resp.getHeaders().get(PapRestControllerV1.REQUEST_ID_NAME)); } @Test public void testAddLoggingHeaders_NonNull() { UUID uuid = UUID.randomUUID(); - Response resp = mockController.addLoggingHeaders(bldr, uuid).build(); - assertEquals(uuid.toString(), resp.getHeaderString(PapRestControllerV1.REQUEST_ID_NAME)); + ResponseEntity resp = mockController.addLoggingHeaders(bldr, uuid).build(); + assertEquals(uuid.toString(), resp.getHeaders().get(PapRestControllerV1.REQUEST_ID_NAME).get(0)); } @Test public void testGetPrincipal() { assertThat(new PapRestControllerV1().getPrincipal()).isEmpty(); - - Principal mockUser = mock(Principal.class, new Returns("myFakeUser")); - when(mockSecurityContext.getUserPrincipal()).thenReturn(mockUser); - - assertEquals("myFakeUser", mockController.getPrincipal()); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java index f64a77b3..9a0f5702 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,6 +79,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); prov = new PdpGroupCreateOrUpdateProvider(); + prov.initialize(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java index 4041de90..3e9eda8a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,7 +92,6 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion()); prov = new MyProvider(); - updater = prov.makeUpdater(session, policy1, fullIdent); } @@ -169,7 +169,9 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group)); when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); - new PdpGroupDeleteProvider().undeploy(fullIdent, DEFAULT_USER); + PdpGroupDeleteProvider deleteProvider = new PdpGroupDeleteProvider(); + deleteProvider.initialize(); + deleteProvider.undeploy(fullIdent, DEFAULT_USER); // should have updated the old group List updates = getGroupUpdates(); @@ -279,6 +281,9 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } private class MyProvider extends PdpGroupDeleteProvider { + private MyProvider() { + super.initialize(); + } @Override protected void process(T request, BiConsumerWithEx processor) throws PfModelException { diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java index d0039c6d..40e37e4f 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,6 +93,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); prov = new PdpGroupDeployProvider(); + prov.initialize(); } /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java index a5f974be..b236c56b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,8 +29,6 @@ import static org.mockito.Mockito.when; import java.io.File; import java.util.List; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.tuple.Pair; import org.junit.Before; import org.junit.Test; @@ -50,6 +48,7 @@ import org.onap.policy.models.pdp.concepts.Pdps; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.springframework.http.HttpStatus; /** * Class to perform unit test of {@link PdpGroupHealthCheckProvider}. @@ -85,8 +84,8 @@ public class TestPdpGroupHealthCheckProvider { @Test public void testFetchPdpGroupHealthStatus() throws Exception { final PdpGroupHealthCheckProvider provider = new PdpGroupHealthCheckProvider(); - final Pair pair = provider.fetchPdpGroupHealthStatus(); - assertEquals(Response.Status.OK, pair.getLeft()); + final Pair pair = provider.fetchPdpGroupHealthStatus(); + assertEquals(HttpStatus.OK, pair.getLeft()); verifyPdps(pair.getRight().getPdpList(), groups); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java index 7d42912f..51bea02a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java @@ -53,6 +53,7 @@ public class TestPolicyAuditProvider extends ProviderSuper { super.setUp(); provider = new PolicyAuditProvider(); + provider.initialize(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java index b49d7704..e07d35c1 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckControllerV1.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2020 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Inc. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,20 +25,16 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.endpoints.parameters.RestClientParameters; -import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.pap.main.parameters.PapParameterGroup; -import org.powermock.reflect.Whitebox; +import org.springframework.beans.factory.annotation.Autowired; /** * Class to perform unit test of {@link PolicyComponentsHealthCheckControllerV1}. @@ -47,29 +44,10 @@ import org.powermock.reflect.Whitebox; public class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestServer { private static final String ENDPOINT = "components/healthcheck"; - private static List savedRestClientParameters; + private List savedRestClientParameters; - /** - * Set up for the test class. - */ - @BeforeClass - public static void setUpClass() { - // To skip calling to the remote components - PapParameterGroup papParameterGroup = ParameterService.get("PapGroup"); - List lo = Whitebox.getInternalState(papParameterGroup, "healthCheckRestClientParameters"); - savedRestClientParameters = new ArrayList<>(lo); - lo.clear(); - } - - /** - * Tear down for the test class. - */ - @AfterClass - public static void tearDownClass() { - PapParameterGroup papParameterGroup = ParameterService.get("PapGroup"); - List lo = Whitebox.getInternalState(papParameterGroup, "healthCheckRestClientParameters"); - lo.addAll(savedRestClientParameters); - } + @Autowired + private PapParameterGroup papParameterGroup; @Test public void testSwagger() throws Exception { @@ -79,6 +57,10 @@ public class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestSe @Test @SuppressWarnings("unchecked") public void testPolicyComponentsHealthCheck() throws Exception { + // take out the other components for healthcheck + savedRestClientParameters = papParameterGroup.getHealthCheckRestClientParameters(); + papParameterGroup.setHealthCheckRestClientParameters(null); + Invocation.Builder invocationBuilder = sendRequest(ENDPOINT); Response response = invocationBuilder.get(); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); @@ -86,5 +68,8 @@ public class TestPolicyComponentsHealthCheckControllerV1 extends CommonPapRestSe result = (Map) response.readEntity(GenericType.forInstance(result)); // No PDP configured, healthy is false assertFalse((Boolean) result.get("healthy")); + + // put back the other components + papParameterGroup.setHealthCheckRestClientParameters(savedRestClientParameters); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java index f27a8d32..13deef40 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java @@ -30,11 +30,11 @@ import static org.mockito.Mockito.when; import java.io.File; import java.net.HttpURLConnection; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.tuple.Pair; import org.junit.After; import org.junit.Before; @@ -44,7 +44,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.common.endpoints.http.client.HttpClientFactory; -import org.onap.policy.common.endpoints.parameters.RestClientParameters; import org.onap.policy.common.endpoints.report.HealthCheckReport; import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.common.utils.coder.Coder; @@ -62,6 +61,8 @@ import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.startstop.PapActivator; +import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; @RunWith(MockitoJUnitRunner.class) public class TestPolicyComponentsHealthCheckProvider { @@ -105,6 +106,8 @@ public class TestPolicyComponentsHealthCheckProvider { private PapParameterGroup savedPapParameterGroup; + private PolicyComponentsHealthCheckProvider provider; + /** * Configures mocks and objects. * @@ -145,15 +148,15 @@ public class TestPolicyComponentsHealthCheckProvider { when(response3.getStatus()).thenReturn(HttpURLConnection.HTTP_OK); when(response3.readEntity(DmaapGetTopicResponse.class)).thenReturn(createDmaapResponse()); when(client3.get()).thenReturn(response3); - + List clients = new ArrayList<>(); + clients.add(client1); + clients.add(client2); + clients.add(client3); PapParameterGroup papParameterGroup = ParameterService.get(PAP_GROUP_PARAMS_NAME); - List params = papParameterGroup.getHealthCheckRestClientParameters(); - when(clientFactory.build(params.get(0))).thenReturn(client1); - when(clientFactory.build(params.get(1))).thenReturn(client2); - when(clientFactory.build(params.get(2))).thenReturn(client3); - - PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup, - clientFactory); + provider = new PolicyComponentsHealthCheckProvider(); + ReflectionTestUtils.setField(provider, "papParameterGroup", papParameterGroup); + provider.initializeClientHealthCheckExecutorService(); + ReflectionTestUtils.setField(provider, "clients", clients); } /** @@ -166,15 +169,14 @@ public class TestPolicyComponentsHealthCheckProvider { } else { ParameterService.deregister(PAP_GROUP_PARAMS_NAME); } - PolicyComponentsHealthCheckProvider.cleanup(); + provider.cleanup(); } @Test public void testFetchPolicyComponentsHealthStatus_allHealthy() { - PolicyComponentsHealthCheckProvider provider = new PolicyComponentsHealthCheckProvider(); - Pair> ret = provider.fetchPolicyComponentsHealthStatus(); - assertEquals(Response.Status.OK, ret.getLeft()); + Pair> ret = provider.fetchPolicyComponentsHealthStatus(); + assertEquals(HttpStatus.OK, ret.getLeft()); assertTrue((Boolean) ret.getRight().get(HEALTHY)); } @@ -239,7 +241,7 @@ public class TestPolicyComponentsHealthCheckProvider { } private Map callFetchPolicyComponentsHealthStatus() { - PolicyComponentsHealthCheckProvider provider = new PolicyComponentsHealthCheckProvider(); + return provider.fetchPolicyComponentsHealthStatus().getRight(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java index d3ff4ea6..8f09b7e3 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java @@ -77,6 +77,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { super.setUp(); prov = new PolicyStatusProvider(); + prov.initialize(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java index 0ca2d4fa..5046181c 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,6 +91,7 @@ public class TestProviderBase extends ProviderSuper { when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); prov = new MyProvider(); + prov.initialize(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java index 0f668bef..e51aa776 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019-2020 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +51,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; -public class End2EndBase extends CommonPapRestServer { +public abstract class End2EndBase extends CommonPapRestServer { private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class); private static final Coder coder = new StandardCoder(); @@ -79,7 +80,7 @@ public class End2EndBase extends CommonPapRestServer { */ @BeforeClass public static void setUpBeforeClass() throws Exception { - CommonPapRestServer.setUpBeforeClass(true); + CommonPapRestServer.setUpBeforeClass(); final PapParameterGroup params = new StandardCoder().decode(new File(CONFIG_FILE), PapParameterGroup.class); daoFactory = new PolicyModelsProviderFactoryWrapper(params.getDatabaseProviderParameters()); @@ -103,7 +104,6 @@ public class End2EndBase extends CommonPapRestServer { logger.warn("failed to close DAO factory", e); } - CommonPapRestServer.teardownAfterClass(); } /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java index d010f1db..d98a4ba3 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java @@ -50,6 +50,9 @@ public class PolicyAuditTest extends End2EndBase { private static final String QUERY_PARAMS_INVALID = "?recordCount=5&startTime=2021-07-25T01:25:15"; private static final String QUERY_PARAMS_CORRECT = "?recordCount=5&startTime=1627219515&endTime=1627478715"; private static final String QUERY_PARAMS_INCORRECT = "?recordCount=5&startTime=1627478715&endTime=1627565115"; + private static int NOT_FOUND_STATUS_CODE = 404; + private static int BAD_REQUEST_STATUS_CODE = 400; + private static final String BAD_REQUEST_MSG = "NumberFormatException For"; @Override @Before @@ -97,7 +100,7 @@ public class PolicyAuditTest extends End2EndBase { // try with invalid date format, should result in error uri = POLICY_AUDIT_ENDPOINT + QUERY_PARAMS_INVALID; - sendAndValidateError(uri, Response.Status.NOT_FOUND.toString()); + sendAndValidateError(uri, BAD_REQUEST_MSG, BAD_REQUEST_STATUS_CODE); } @Test @@ -114,11 +117,11 @@ public class PolicyAuditTest extends End2EndBase { // try with incorrect dates in query, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + QUERY_PARAMS_INCORRECT; - sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND); + sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND, NOT_FOUND_STATUS_CODE); // try with invalid date format, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + QUERY_PARAMS_INVALID; - sendAndValidateError(uri, Response.Status.NOT_FOUND.toString()); + sendAndValidateError(uri, BAD_REQUEST_MSG, BAD_REQUEST_STATUS_CODE); } @Test @@ -138,12 +141,12 @@ public class PolicyAuditTest extends End2EndBase { // try with incorrect dates in query, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_INCORRECT; - sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND); + sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND, NOT_FOUND_STATUS_CODE); // try with invalid date format, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_INVALID; - sendAndValidateError(uri, Response.Status.NOT_FOUND.toString()); + sendAndValidateError(uri, BAD_REQUEST_MSG, BAD_REQUEST_STATUS_CODE); } @Test @@ -162,12 +165,12 @@ public class PolicyAuditTest extends End2EndBase { // try with incorrect dates in query, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_INCORRECT; - sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND); + sendAndValidateError(uri, PolicyAuditControllerV1.NO_AUDIT_RECORD_FOUND, NOT_FOUND_STATUS_CODE); // try with invalid date format, should result in error uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion() + QUERY_PARAMS_INVALID; - sendAndValidateError(uri, Response.Status.NOT_FOUND.toString()); + sendAndValidateError(uri, BAD_REQUEST_MSG, BAD_REQUEST_STATUS_CODE); } private void sendAndValidateSuccess(String uri, int count) throws Exception { @@ -193,10 +196,10 @@ public class PolicyAuditTest extends End2EndBase { } } - private void sendAndValidateError(String uri, String errorMessage) throws Exception { + private void sendAndValidateError(String uri, String errorMessage, int statusCode) throws Exception { Invocation.Builder invocationBuilder = sendRequest(uri); Response rawresp = invocationBuilder.get(); - assertThat(rawresp.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); + assertThat(rawresp.getStatus()).isEqualTo(statusCode); String resp = rawresp.readEntity(String.class); assertThat(resp).contains(errorMessage); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java index 0f1b560f..1331e458 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +39,10 @@ import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.pap.main.parameters.CommonTestData; +import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.rest.PapStatisticsManager; import org.onap.policy.pap.main.rest.StatisticsReport; @@ -57,10 +60,10 @@ public class StatisticsTest extends End2EndBase { public static void setUpBeforeClass() throws Exception { End2EndBase.setUpBeforeClass(); - PolicyModelsProviderFactoryWrapper modelProviderWrapper = - Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { + PolicyModelsProviderFactory modelProviderWrapper = new PolicyModelsProviderFactory(); + PapParameterGroup parameterGroup = new CommonTestData().getPapParameterGroup(6969); + try (PolicyModelsProvider databaseProvider = + modelProviderWrapper.createPolicyModelsProvider(parameterGroup.getDatabaseProviderParameters())) { PdpStatistics pdpStatisticsRecord = new PdpStatistics(); pdpStatisticsRecord.setPdpGroupName("defaultGroup"); pdpStatisticsRecord.setPdpSubGroupName("apex"); diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java deleted file mode 100644 index a83be4fb..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.startstop; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.nio.charset.StandardCharsets; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.common.utils.resources.MessageConstants; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyPapRuntimeException; -import org.onap.policy.pap.main.parameters.CommonTestData; - -/** - * Class to perform unit test of {@link Main}}. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class TestMain { - private static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParams.json"; - - private static int port; - - private Main main; - - /** - * Allocates a new DB name, server port, and creates a config file. - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - CommonTestData.newDb(); - port = NetworkUtil.allocPort(); - - String json = new CommonTestData().getPapParameterGroupAsString(port); - - File file = new File(CONFIG_FILE); - file.deleteOnExit(); - - try (FileOutputStream output = new FileOutputStream(file)) { - output.write(json.getBytes(StandardCharsets.UTF_8)); - } - } - - /** - * Set up. - */ - @Before - public void setUp() throws Exception { - Registry.newRegistry(); - HttpServletServerFactoryInstance.getServerFactory().destroy(); - } - - /** - * Shuts "main" down. - * - */ - @After - public void tearDown() { - // shut down activator - PapActivator activator = Registry.getOrDefault(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class, null); - if (activator != null && activator.isAlive()) { - activator.stop(); - } - } - - private void testMainBody(String[] papConfigParameters) { - main = new Main(papConfigParameters); - assertTrue(main.getParameters().isValid()); - assertEquals(CommonTestData.PAP_GROUP_NAME, main.getParameters().getName()); - - // ensure items were added to the registry - assertNotNull(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class)); - main.shutdown(); - } - - @Test - public void testMain() { - final String[] papConfigParameters = {"-c", CONFIG_FILE}; - testMainBody(papConfigParameters); - } - - @Test - public void testMainCustomGroup() { - final String[] papConfigParameters = { - "-c", - CONFIG_FILE, - "-g", - "parameters/PapDbGroup1.json" - }; - testMainBody(papConfigParameters); - } - - @Test - public void testMainPapDb() { - final String[] papConfigParameters = { - "-c", - CONFIG_FILE, - "-g", - "PapDb.json" - }; - testMainBody(papConfigParameters); - } - - @Test - public void testMain_NoArguments() { - final String[] papConfigParameters = {}; - assertThatThrownBy(() -> new Main(papConfigParameters)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_PAP)); - } - - @Test - public void testMain_InvalidArguments() { - final String[] papConfigParameters = {CONFIG_FILE}; - assertThatThrownBy(() -> new Main(papConfigParameters)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_PAP)); - } - - @Test - public void testMain_Help() { - final String[] papConfigParameters = {"-h"}; - main = new Main(papConfigParameters); - assertNull(main.getParameters()); - } - - @Test - public void testMain_InvalidParameters() { - final String[] papConfigParameters = {"-c", "parameters/PapConfigParameters_InvalidName.json"}; - assertThatThrownBy(() -> new Main(papConfigParameters)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_PAP)); - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java index 63ca52a8..1a1415a5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +45,6 @@ import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; -import org.onap.policy.pap.main.parameters.PapParameterHandler; import org.onap.policy.pap.main.rest.PapStatisticsManager; @@ -89,9 +89,7 @@ public class TestPapActivator { output.write(json.getBytes(StandardCharsets.UTF_8)); } - final String[] papConfigParameters = {"-c", CONFIG_FILE}; - final PapCommandLineArguments arguments = new PapCommandLineArguments(papConfigParameters); - final PapParameterGroup parGroup = new PapParameterHandler().getParameters(arguments); + final PapParameterGroup parGroup = new CommonTestData().getPapParameterGroup(6969); activator = new PapActivator(parGroup); } diff --git a/main/src/test/resources/config/application.yaml b/main/src/test/resources/config/application.yaml new file mode 100644 index 00000000..1444a7d2 --- /dev/null +++ b/main/src/test/resources/config/application.yaml @@ -0,0 +1,81 @@ +spring: + security: + user: + name: policyadmin + password: zb!XztG34 + http: + converters: + preferred-json-mapper: gson + +server: + port: 6969 + +pap: + name: "PapGroup" + pdpParameters: + updateParameters: + maxRetryCount: 1 + maxWaitMs: 3000 + stateChangeParameters: + maxRetryCount: 1 + maxWaitMs: 3000 + heartBeatMs: 6000 + maxMessageAgeMs: 20000 + databaseProviderParameters: + name: PolicyModelsProviderParameters + implementation: org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl + databaseDriver: org.h2.Driver + databaseUrl: jdbc:h2:mem:testdb0 + databaseUser: policy + databasePassword: UDAxaWNZ + persistenceUnit: ToscaConceptTest + savePdpStatisticsInDb: true + topicParameterGroup: + topicSources: + - topic: POLICY-PDP-PAP + servers: + - message-router + topicCommInfrastructure: noop + - topic: POLICY-HEARTBEAT + effectiveTopic: POLICY-PDP-PAP + consumerGroup: policy-pap + servers: + - message-router + topicCommInfrastructure: noop + topicSinks: + - topic: POLICY-PDP-PAP + servers: + - message-router + topicCommInfrastructure: noop + - topic: POLICY-NOTIFICATION + servers: + - message-router + topicCommInfrastructure: noop + healthCheckRestClientParameters: + - clientName: api + hostname: policy-api + port: 6969 + userName: policyadmin + password: zb!XztG34 + useHttps: true + basePath: policy/api/v1/healthcheck + - clientName: distribution + hostname: policy-distribution + port: 6969 + userName: healthcheck + password: zb!XztG34 + useHttps: true + basePath: healthcheck + - clientName: dmaap + hostname: message-router + port: 3905 + useHttps: true + basePath: topics + +management: + endpoints: + web: + base-path: / + exposure: + include: health, metrics, prometheus + path-mapping.prometheus: metrics diff --git a/packages/policy-pap-docker/pom.xml b/packages/policy-pap-docker/pom.xml index 6e6a66e3..2de149e0 100644 --- a/packages/policy-pap-docker/pom.xml +++ b/packages/policy-pap-docker/pom.xml @@ -1,7 +1,7 @@