diff options
Diffstat (limited to 'main/src/main')
40 files changed, 999 insertions, 989 deletions
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<ErrorResponse> pfModelExceptionHandler(PfModelException exp, WebRequest req) { + return handlePfModelException(exp, exp.getErrorResponse(), req); + } + + /** + * Handle PfModelRuntimeException. + * + * @return ResponseEntity the response + */ + @ExceptionHandler(PfModelRuntimeException.class) + public ResponseEntity<ErrorResponse> pfModelRuntimeExceptionHandler(PfModelRuntimeException exp, WebRequest req) { + return handlePfModelException(exp, exp.getErrorResponse(), req); + } + + private ResponseEntity<ErrorResponse> 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<String> 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<HealthCheckReport> 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<PdpGroupUpdateResponse> 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<PdpGroupUpdateResponse> 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,17 +61,11 @@ import org.slf4j.LoggerFactory; * <li>PAP DAO Factory</li> * </ul> */ +@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. * * @param groups PDP group configurations to be created or updated 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<PdpGroupDeleteResponse> 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<PdpGroupDeployResponse> 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<PdpGroupDeployResponse> 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<PdpGroupDeleteResponse> 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<PdpGroupDeployResponse> 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<PdpGroupDeployResponse> 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<PdpGroupDeployResponse> 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<PdpGroupDeployResponse> 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; * <li>PAP DAO Factory</li> * </ul> */ +@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<Status, Pdps> 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<Pdps> pdpGroupHealthCheck(@ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) throws PfModelException { + Pair<HttpStatus, Pdps> 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<Response.Status, Pdps> fetchPdpGroupHealthStatus() throws PfModelException { + public Pair<HttpStatus, Pdps> 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<PdpGroups> 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<Status, PdpGroups> 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<HttpStatus, PdpGroups> 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<Response.Status, PdpGroups> fetchPdpGroupDetails() throws PfModelException { + public Pair<HttpStatus, PdpGroups> 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<PdpGroupStateChangeResponse> 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<Status, PdpGroupStateChangeResponse> 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<HttpStatus, PdpGroupStateChangeResponse> 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<Response.Status, PdpGroupStateChangeResponse> changeGroupState(final String groupName, + public Pair<HttpStatus, PdpGroupStateChangeResponse> 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<Collection<PolicyAudit>> 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<Object> 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<Object> 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<Object> 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<PolicyAudit> result) { + private ResponseEntity<Object> makeOkOrNotFoundResponse(UUID requestId, Collection<PolicyAudit> 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<Status, Map<String, Object>> pair = - provider.fetchPolicyComponentsHealthStatus(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); + public ResponseEntity<Map<String, Object>> policyComponentsHealthCheck( + @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) @RequestHeader( + required = false, + value = REQUEST_ID_NAME) final UUID requestId) { + final Pair<HttpStatus, Map<String, Object>> 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<HttpClient> 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)); @@ -93,11 +103,20 @@ public class PolicyComponentsHealthCheckProvider { } /** + * 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<Status, Map<String, Object>> fetchPolicyComponentsHealthStatus() { + public Pair<HttpStatus, Map<String, Object>> fetchPolicyComponentsHealthStatus() { boolean isHealthy; Map<String, Object> 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<String, List<Pdp>> fetchPdpsHealthStatus(List<PdpGroup> 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<Object> 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<PolicyStatus> 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<Object> 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<PolicyStatus> 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<Object> 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<PolicyStatus> 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<Object> 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<Object> 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<PdpPolicyStatus> 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<Object> 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<PdpPolicyStatus> 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<Object> 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<PdpPolicyStatus> 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<Object> makeNotFoundResponse(final UUID requestId) { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.NOT_FOUND)), requestId) .build(); } - private Response makeRegexNotFoundResponse(UUID requestId) { + private ResponseEntity<Object> 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<Object> 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<StatisticsReport> 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<Map<String, Map<String, List<PdpStatistics>>>> 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<Map<String, Map<String, List<PdpStatistics>>>> 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<Map<String, Map<String, List<PdpStatistics>>>> 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<Map<String, Map<String, List<PdpStatistics>>>> 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<ScheduledExecutorService> pdpExpirationTimer = new AtomicReference<>(); final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>(); final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>(); - final AtomicReference<RestServer> restServer = new AtomicReference<>(); final AtomicReference<PolicyNotifier> 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 |