diff options
Diffstat (limited to 'main/src/main/java/org/onap/policy/pap/main/rest')
25 files changed, 611 insertions, 604 deletions
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"; |