Add apis for policy audit 07/122807/2
authorRam Krishna Verma <ram_krishna.verma@bell.ca>
Wed, 21 Jul 2021 22:24:57 +0000 (18:24 -0400)
committerRam Krishna Verma <ram_krishna.verma@bell.ca>
Thu, 22 Jul 2021 19:48:15 +0000 (15:48 -0400)
Adding api's to fetch policy audit records from db.
This is as per the design documented here -
https://wiki.onap.org/display/DW/PAP+REST+API+changes+for+Istanbul+release

Issue-ID: POLICY-3340
Change-Id: Iff80ab695d17ec38d4fe8ab98c0b95048cbae448
Signed-off-by: Ram Krishna Verma <ram_krishna.verma@bell.ca>
main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java
main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditControllerV1.java [new file with mode: 0644]
main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java [new file with mode: 0644]
main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java [new file with mode: 0644]

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
new file mode 100644 (file)
index 0000000..e669594
--- /dev/null
@@ -0,0 +1,330 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+import io.swagger.annotations.Authorization;
+import io.swagger.annotations.Extension;
+import io.swagger.annotations.ExtensionProperty;
+import io.swagger.annotations.ResponseHeader;
+import java.util.Collection;
+import java.util.Date;
+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 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;
+
+/**
+ * Class to provide REST end points for PAP component to retrieve the audit information for
+ * various operations on policies.
+ */
+public class PolicyAuditControllerV1 extends PapRestControllerV1 {
+    private static final String GET_AUDIT_RECORD_FAILED = "get audit records failed";
+
+    private static final Logger logger = LoggerFactory.getLogger(PolicyAuditControllerV1.class);
+
+    private final PolicyAuditProvider provider = new PolicyAuditProvider();
+
+    /**
+     * Queries audit information of all policies.
+     *
+     * @param requestId request ID used in ONAP logging
+     * @param recordCount number of records to fetch
+     * @param fromDate the starting date for the query
+     * @param toDate the ending date for the query
+     * @return a response
+     */
+    // @formatter:off
+    @GET
+    @Path("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",
+        responseContainer = "List", response = PolicyAudit.class,
+        tags = {"Policy Administration (PAP) API"},
+        authorizations = @Authorization(value = AUTHORIZATION_TYPE),
+        responseHeaders = {
+            @ResponseHeader(name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION,
+                            response = UUID.class)},
+        extensions = {
+            @Extension(name = EXTENSION_NAME,
+                properties = {
+                    @ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION),
+                    @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)
+                })
+            })
+    @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)
+    })
+    // @formatter:on
+
+    public Response getAllAuditRecords(
+                    @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 = "From Date", required = false) @QueryParam("fromDate") final Date fromDate,
+                    @ApiParam(value = "To Date", required = false) @QueryParam("toDate") final Date toDate) {
+
+        try {
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                            .entity(provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount)
+                                            .fromDate((fromDate == null ? null : fromDate.toInstant()))
+                                            .toDate((toDate == null ? null : toDate.toInstant())).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();
+        }
+    }
+
+    /**
+     * Queries audit information of policies in a specific PdpGroup.
+     *
+     * @param requestId request ID used in ONAP logging
+     * @param recordCount number of records to fetch
+     * @param fromDate the starting date for the query
+     * @param toDate the ending date for the query
+     * @param pdpGroupName the pdp group name for the query
+     * @return a response
+     */
+    // @formatter:off
+    @GET
+    @Path("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",
+        responseContainer = "List", response = PolicyAudit.class,
+        tags = {"Policy Administration (PAP) API"},
+        authorizations = @Authorization(value = AUTHORIZATION_TYPE),
+        responseHeaders = {
+            @ResponseHeader(name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION,
+                            response = UUID.class)},
+        extensions = {
+            @Extension(name = EXTENSION_NAME,
+                properties = {
+                    @ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION),
+                    @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)
+                })
+            })
+    @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)
+    })
+    // @formatter:on
+
+    public Response getAuditRecordsByGroup(
+                    @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 = "From Date", required = false) @QueryParam("fromDate") final Date fromDate,
+                    @ApiParam(value = "To Date", required = false) @QueryParam("toDate") final Date toDate,
+                    @ApiParam(value = "PDP Group Name",
+                                    required = true) @PathParam("pdpGroupName") String pdpGroupName) {
+
+        try {
+            return makeOkOrNotFoundResponse(requestId, provider.getAuditRecords(AuditFilter.builder()
+                            .recordNum(recordCount).fromDate((fromDate == null ? null : fromDate.toInstant()))
+                            .toDate((toDate == null ? null : toDate.toInstant())).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();
+        }
+    }
+
+    /**
+     * Queries audit information of a specific version of a policy in a PdpGroup.
+     *
+     * @param requestId request ID used in ONAP logging
+     * @param recordCount number of records to fetch
+     * @param fromDate the starting date for the query
+     * @param toDate the ending date for the query
+     * @param pdpGroupName the pdp group name for the query
+     * @param policyName name of the Policy
+     * @param policyVersion version of the Policy
+     * @return a response
+     */
+    // @formatter:off
+    @GET
+    @Path("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",
+        response = PolicyAudit.class,
+        tags = {"Policy Administration (PAP) API"},
+        authorizations = @Authorization(value = AUTHORIZATION_TYPE),
+        responseHeaders = {
+            @ResponseHeader(name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION,
+                            response = UUID.class)},
+        extensions = {
+            @Extension(name = EXTENSION_NAME,
+                properties = {
+                    @ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION),
+                    @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)
+                })
+            })
+    @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)
+    })
+    // @formatter:on
+
+    public Response getAuditRecordsOfPolicy(
+                    @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 = "From Date", required = false) @QueryParam("fromDate") final Date fromDate,
+                    @ApiParam(value = "To Date", required = false) @QueryParam("toDate") final Date toDate,
+                    @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) {
+
+        try {
+            return makeOkOrNotFoundResponse(requestId,
+                            provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount)
+                                            .fromDate((fromDate == null ? null : fromDate.toInstant()))
+                                            .toDate((toDate == null ? null : toDate.toInstant())).pdpGroup(pdpGroupName)
+                                            .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();
+        }
+    }
+
+    /**
+     * Queries audit information of a specific version of a policy.
+     *
+     * @param requestId request ID used in ONAP logging
+     * @param recordCount number of records to fetch
+     * @param fromDate the starting date for the query
+     * @param toDate the ending date for the query
+     * @param policyName name of the Policy
+     * @param policyVersion version of the Policy
+     * @return a response
+     */
+    // @formatter:off
+    @GET
+    @Path("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",
+        response = PolicyAudit.class,
+        tags = {"Policy Administration (PAP) API"},
+        authorizations = @Authorization(value = AUTHORIZATION_TYPE),
+        responseHeaders = {
+            @ResponseHeader(name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION,
+                            response = String.class),
+            @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION,
+                            response = UUID.class)},
+        extensions = {
+            @Extension(name = EXTENSION_NAME,
+                properties = {
+                    @ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION),
+                    @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)
+                })
+            })
+    @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)
+    })
+    // @formatter:on
+
+    public Response getAuditRecordsOfPolicy(
+                    @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 = "From Date", required = false) @QueryParam("fromDate") final Date fromDate,
+                    @ApiParam(value = "To Date", required = false) @QueryParam("toDate") final Date toDate,
+                    @ApiParam(value = "Policy Id", 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((fromDate == null ? null : fromDate.toInstant()))
+                                            .toDate((toDate == null ? null : toDate.toInstant())).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();
+        }
+    }
+
+    private Response makeOkOrNotFoundResponse(UUID requestId, Collection<PolicyAudit> result) {
+        if (result.isEmpty()) {
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.NOT_FOUND)), requestId)
+                            .build();
+        } else {
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                            .entity(result).build();
+        }
+    }
+}
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
new file mode 100644 (file)
index 0000000..6da8b07
--- /dev/null
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import java.util.Collection;
+import org.onap.policy.common.utils.services.Registry;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.pap.concepts.PolicyAudit;
+import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.pap.main.PapConstants;
+import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
+
+/**
+ * Provider for PAP component to query policy audit information.
+ */
+public class PolicyAuditProvider {
+
+    /**
+     * Factory for PAP DAO.
+     */
+    private final PolicyModelsProviderFactoryWrapper daoFactory;
+
+
+    /**
+     * Constructs the object.
+     */
+    public PolicyAuditProvider() {
+        this.daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class);
+    }
+
+    /**
+     * Gets the audit record of all policies.
+     *
+     * @param auditFilter the filter for the query
+     * @return the audit record of all policies
+     * @throws PfModelException if a DB error occurs
+     */
+    public Collection<PolicyAudit> getAuditRecords(AuditFilter auditFilter)
+                    throws PfModelException {
+        try (PolicyModelsProvider dao = daoFactory.create()) {
+            return dao.getAuditRecords(auditFilter);
+        }
+    }
+}
index 3b08940..ad78fc7 100644 (file)
@@ -60,6 +60,7 @@ import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1;
 import org.onap.policy.pap.main.rest.PdpGroupHealthCheckControllerV1;
 import org.onap.policy.pap.main.rest.PdpGroupQueryControllerV1;
 import org.onap.policy.pap.main.rest.PdpGroupStateChangeControllerV1;
+import org.onap.policy.pap.main.rest.PolicyAuditControllerV1;
 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckControllerV1;
 import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckProvider;
 import org.onap.policy.pap.main.rest.PolicyStatusControllerV1;
@@ -270,7 +271,8 @@ public class PapActivator extends ServiceManagerContainer {
                                 PdpGroupQueryControllerV1.class,
                                 PdpGroupHealthCheckControllerV1.class,
                                 PolicyStatusControllerV1.class,
-                                PolicyComponentsHealthCheckControllerV1.class);
+                                PolicyComponentsHealthCheckControllerV1.class,
+                                PolicyAuditControllerV1.class);
                 restServer.set(server);
                 restServer.get().start();
             },
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditControllerV1.java
new file mode 100644 (file)
index 0000000..5683352
--- /dev/null
@@ -0,0 +1,70 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import static org.junit.Assert.assertEquals;
+
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.Response;
+import org.junit.Test;
+
+/**
+ * Note: this tests failure cases; success cases are tested by tests in the "e2e" package.
+ */
+public class TestPolicyAuditControllerV1 extends CommonPapRestServer {
+
+    private static final String POLICY_AUDIT_ENDPOINT = "policies/audit";
+
+    @Test
+    public void testSwagger() throws Exception {
+
+        super.testSwagger(POLICY_AUDIT_ENDPOINT);
+        super.testSwagger(POLICY_AUDIT_ENDPOINT + "/{pdpGroupName}");
+        super.testSwagger(POLICY_AUDIT_ENDPOINT + "/{pdpGroupName}/{policyName}/{policyVersion}");
+        super.testSwagger(POLICY_AUDIT_ENDPOINT + "/{policyName}/{policyVersion}");
+    }
+
+    @Test
+    public void testGetAllAuditRecords() throws Exception {
+        String uri = POLICY_AUDIT_ENDPOINT;
+
+        // verify it fails when no authorization info is included
+        checkUnauthRequest(uri, req -> req.get());
+    }
+
+    @Test
+    public void testGetAuditRecordsByGroup() throws Exception {
+        checkRequest(POLICY_AUDIT_ENDPOINT + "/my-group-name");
+    }
+
+    @Test
+    public void testGetAuditRecordsOfPolicy() throws Exception {
+        checkRequest(POLICY_AUDIT_ENDPOINT + "/my-group-name/my-name/1.2.3");
+        checkRequest(POLICY_AUDIT_ENDPOINT + "/my-name/1.2.3");
+    }
+
+    private void checkRequest(String uri) throws Exception {
+        Invocation.Builder invocationBuilder = sendRequest(uri);
+        Response rawresp = invocationBuilder.get();
+        assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus());
+
+        // verify it fails when no authorization info is included
+        checkUnauthRequest(uri, req -> req.get());
+    }
+}
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java
new file mode 100644 (file)
index 0000000..7d42912
--- /dev/null
@@ -0,0 +1,104 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.utils.services.Registry;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.pap.concepts.PolicyAudit;
+import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction;
+import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
+
+public class TestPolicyAuditProvider extends ProviderSuper {
+    private static final String TEST_GROUP = "testGroup";
+    private static final String TEST_PDP_TYPE = "testPdpType";
+    private static final ToscaConceptIdentifier POLICY_A = new ToscaConceptIdentifier("PolicyA", "1.0.0");
+    private static final ToscaConceptIdentifier POLICY_B = new ToscaConceptIdentifier("PolicyB", "2.0.0");
+
+    private PolicyAuditProvider provider;
+
+    @AfterClass
+    public static void tearDownAfterClass() {
+        Registry.newRegistry();
+    }
+
+    @Override
+    @Before
+    public void setUp() throws Exception {
+
+        super.setUp();
+        provider = new PolicyAuditProvider();
+    }
+
+    @Test
+    public void testGetAuditRecords() throws PfModelException {
+
+        AuditFilter auditFilter = AuditFilter.builder().recordNum(5).fromDate(null).toDate(null).build();
+
+        buildAuditRecords(auditFilter);
+
+        List<PolicyAudit> result = new ArrayList<>(provider.getAuditRecords(auditFilter));
+        validateAuditRecords(result, 2);
+    }
+
+    private void buildAuditRecords(AuditFilter auditFilter) {
+        PolicyAudit audit1 = PolicyAudit.builder().auditId(123L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE)
+                        .policy(POLICY_A).action(AuditAction.DEPLOYMENT).timestamp(Instant.now()).user(DEFAULT_USER)
+                        .build();
+
+        PolicyAudit audit2 = PolicyAudit.builder().auditId(456L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE)
+                        .policy(POLICY_B).action(AuditAction.UNDEPLOYMENT).timestamp(Instant.now()).user(DEFAULT_USER)
+                        .build();
+
+        if (auditFilter.getName() == null) {
+            when(dao.getAuditRecords(auditFilter)).thenReturn(List.of(audit1, audit2));
+        } else {
+            when(dao.getAuditRecords(auditFilter)).thenReturn(List.of(audit1));
+        }
+
+    }
+
+    private void validateAuditRecords(List<PolicyAudit> result, int count) {
+        assertThat(result).hasSize(count);
+        for (PolicyAudit audit : result) {
+            if (audit.getAuditId() == 123L) {
+                assertThat(audit.getPdpGroup()).isEqualTo(TEST_GROUP);
+                assertThat(audit.getPdpType()).isEqualTo(TEST_PDP_TYPE);
+                assertThat(audit.getPolicy()).isEqualTo(POLICY_A);
+                assertThat(audit.getAction()).isEqualTo(AuditAction.DEPLOYMENT);
+                assertThat(audit.getUser()).isEqualTo(DEFAULT_USER);
+            } else if (audit.getAuditId() == 456L) {
+                assertThat(audit.getPdpGroup()).isEqualTo(TEST_GROUP);
+                assertThat(audit.getPdpType()).isEqualTo(TEST_PDP_TYPE);
+                assertThat(audit.getPolicy()).isEqualTo(POLICY_B);
+                assertThat(audit.getAction()).isEqualTo(AuditAction.UNDEPLOYMENT);
+                assertThat(audit.getUser()).isEqualTo(DEFAULT_USER);
+            }
+        }
+    }
+}
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java
new file mode 100644 (file)
index 0000000..c4de1f4
--- /dev/null
@@ -0,0 +1,145 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest.e2e;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.Response;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.utils.services.Registry;
+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.concepts.PolicyAudit.AuditAction;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
+import org.onap.policy.pap.main.PapConstants;
+import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
+
+public class PolicyAuditTest extends End2EndBase {
+    private static final String TEST_GROUP = "testGroup";
+    private static final String TEST_PDP_TYPE = "testPdpType";
+    private static final ToscaConceptIdentifier POLICY_A = new ToscaConceptIdentifier("PolicyA", "1.0.0");
+    private static final ToscaConceptIdentifier POLICY_B = new ToscaConceptIdentifier("PolicyB", "2.0.0");
+    private static final String DEFAULT_USER = "TEST";
+    private static final String POLICY_AUDIT_ENDPOINT = "policies/audit";
+    private static final String URI_SEPERATOR = "/";
+
+    @Override
+    @Before
+    public void setUp() throws Exception {
+        super.setUp();
+        setupEnv();
+    }
+
+    private void setupEnv() {
+        List<PolicyAudit> recordList = new ArrayList<>();
+        PolicyModelsProviderFactoryWrapper modelProviderWrapper =
+                        Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class);
+
+        try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) {
+            PolicyAudit audit1 = PolicyAudit.builder().auditId(123L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE)
+                            .policy(POLICY_A).action(AuditAction.DEPLOYMENT).timestamp(Instant.now()).user(DEFAULT_USER)
+                            .build();
+            PolicyAudit audit2 = PolicyAudit.builder().auditId(456L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE)
+                            .policy(POLICY_B).action(AuditAction.UNDEPLOYMENT).timestamp(Instant.now())
+                            .user(DEFAULT_USER).build();
+            recordList.add(audit1);
+            recordList.add(audit2);
+            databaseProvider.createAuditRecords(recordList);
+        } catch (final PfModelException exp) {
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, exp.getMessage());
+        }
+    }
+
+    @Test
+    public void testGetAllAuditRecords() throws Exception {
+        String uri = POLICY_AUDIT_ENDPOINT;
+
+        Invocation.Builder invocationBuilder = sendRequest(uri);
+        Response rawresp = invocationBuilder.get();
+        assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
+
+        List<PolicyAudit> resp = rawresp.readEntity(new GenericType<List<PolicyAudit>>() {});
+        validateAuditRecords(resp, 2);
+    }
+
+    @Test
+    public void testGetAuditRecordsByGroup() throws Exception {
+        String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP;
+
+        Invocation.Builder invocationBuilder = sendRequest(uri);
+        Response rawresp = invocationBuilder.get();
+        assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
+
+        List<PolicyAudit> resp = rawresp.readEntity(new GenericType<List<PolicyAudit>>() {});
+        validateAuditRecords(resp, 2);
+    }
+
+    @Test
+    public void testGetAuditRecordsOfPolicyWithGroup() throws Exception {
+        String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + TEST_GROUP + URI_SEPERATOR + POLICY_A.getName()
+                        + URI_SEPERATOR + POLICY_A.getVersion();
+
+        Invocation.Builder invocationBuilder = sendRequest(uri);
+        Response rawresp = invocationBuilder.get();
+        assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
+
+        List<PolicyAudit> resp = rawresp.readEntity(new GenericType<List<PolicyAudit>>() {});
+        validateAuditRecords(resp, 1);
+    }
+
+    @Test
+    public void testGetAuditRecordsOfPolicyWithoutGroup() throws Exception {
+        String uri = POLICY_AUDIT_ENDPOINT + URI_SEPERATOR + POLICY_A.getName() + URI_SEPERATOR + POLICY_A.getVersion();
+
+        Invocation.Builder invocationBuilder = sendRequest(uri);
+        Response rawresp = invocationBuilder.get();
+        assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
+
+        List<PolicyAudit> resp = rawresp.readEntity(new GenericType<List<PolicyAudit>>() {});
+        validateAuditRecords(resp, 1);
+    }
+
+    private void validateAuditRecords(List<PolicyAudit> result, int count) {
+        assertThat(result).hasSize(count);
+        for (PolicyAudit audit : result) {
+            if (audit.getAuditId() == 123L) {
+                assertThat(audit.getPdpGroup()).isEqualTo(TEST_GROUP);
+                assertThat(audit.getPdpType()).isEqualTo(TEST_PDP_TYPE);
+                assertThat(audit.getPolicy()).isEqualTo(POLICY_A);
+                assertThat(audit.getAction()).isEqualTo(AuditAction.DEPLOYMENT);
+                assertThat(audit.getUser()).isEqualTo(DEFAULT_USER);
+            } else if (audit.getAuditId() == 456L) {
+                assertThat(audit.getPdpGroup()).isEqualTo(TEST_GROUP);
+                assertThat(audit.getPdpType()).isEqualTo(TEST_PDP_TYPE);
+                assertThat(audit.getPolicy()).isEqualTo(POLICY_B);
+                assertThat(audit.getAction()).isEqualTo(AuditAction.UNDEPLOYMENT);
+                assertThat(audit.getUser()).isEqualTo(DEFAULT_USER);
+            }
+        }
+    }
+}