Implement policy provider functions 71/83971/5
authorChenfei Gao <cgao@research.att.com>
Tue, 2 Apr 2019 12:55:17 +0000 (08:55 -0400)
committerChenfei Gao <cgao@research.att.com>
Wed, 3 Apr 2019 20:56:17 +0000 (16:56 -0400)
Includes:
a) Implement policy provider functions
b) Implement policy type provider functions
c) Implement legacy guard policy provider functions
d) Implement legacy operational policy provider functions
e) Modify API endpoints to align with provider functions
f) Hook up API statistics counter

Junit tests for providers and new endpoints will be in next patch/review.

Issue-ID: POLICY-1441
Change-Id: I113de95f6e0ea5f5436c072536f5e9a178988e5e
Signed-off-by: Chenfei Gao <cgao@research.att.com>
31 files changed:
main/pom.xml
main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java
main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
main/src/main/java/org/onap/policy/api/main/rest/ApiRestServer.java
main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java
main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java
main/src/main/resources/META-INF/persistence.xml [new file with mode: 0644]
main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java
main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java
main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java
main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java
main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java [moved from main/src/test/java/org/onap/policy/api/main/exception/PolicyApiRuntimeExceptionTest.java with 55% similarity]
main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java [new file with mode: 0644]
main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java [new file with mode: 0644]
main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java [new file with mode: 0644]
main/src/test/resources/META-INF/persistence.xml [new file with mode: 0644]
main/src/test/resources/parameters/ApiConfigParameters.json
main/src/test/resources/parameters/ApiConfigParameters_Https.json
main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json
main/src/test/resources/parameters/MinimumParameters.json
main/src/test/resources/parameters/NoParameters.json
main/src/test/resources/policies/vDNS.policy.guard.minmax.input.json
main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.json [new file with mode: 0644]
main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml
main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json [new file with mode: 0644]
main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml
packages/policy-api-tarball/src/main/resources/etc/defaultConfig.json
packages/policy-api-tarball/src/main/resources/etc/s3pConfig.json

index db30611..381d39f 100644 (file)
             <artifactId>lombok</artifactId>
             <scope>provided</scope>
         </dependency>
+        <dependency>
+            <groupId>com.h2database</groupId>
+            <artifactId>h2</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mariadb.jdbc</groupId>
+            <artifactId>mariadb-java-client</artifactId>
+        </dependency>
     </dependencies>
 
     <build>
index af12f01..9727b23 100644 (file)
@@ -24,23 +24,28 @@ import org.onap.policy.common.parameters.GroupValidationResult;
 import org.onap.policy.common.parameters.ParameterGroup;
 import org.onap.policy.common.parameters.ValidationStatus;
 import org.onap.policy.common.utils.validation.ParameterValidationUtils;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 
 /**
  * Class to hold all parameters needed for Api component.
  *
  */
 public class ApiParameterGroup implements ParameterGroup {
+
     private String name;
     private RestServerParameters restServerParameters;
+    private PolicyModelsProviderParameters databaseProviderParameters;
 
     /**
      * Create the api parameter group.
      *
      * @param name the parameter group name
      */
-    public ApiParameterGroup(final String name, final RestServerParameters restServerParameters) {
+    public ApiParameterGroup(final String name, final RestServerParameters restServerParameters,
+            final PolicyModelsProviderParameters databaseProviderParameters) {
         this.name = name;
         this.restServerParameters = restServerParameters;
+        this.databaseProviderParameters = databaseProviderParameters;
     }
 
     /**
@@ -72,6 +77,15 @@ public class ApiParameterGroup implements ParameterGroup {
         return restServerParameters;
     }
 
+    /**
+     * Return the databaseProviderParameters of this parameter group instance.
+     *
+     * @return the databaseProviderParameters
+     */
+    public PolicyModelsProviderParameters getDatabaseProviderParameters() {
+        return databaseProviderParameters;
+    }
+
     /**
      * Validate the parameter group.
      *
@@ -89,6 +103,12 @@ public class ApiParameterGroup implements ParameterGroup {
         } else {
             validationResult.setResult("restServerParameters", restServerParameters.validate());
         }
+        if (databaseProviderParameters == null) {
+            validationResult.setResult("databaseProviderParameters", ValidationStatus.INVALID,
+                    "must have databaseProviderParameters to configure api rest server");
+        } else {
+            validationResult.setResult("databaseProviderParameters", databaseProviderParameters.validate());
+        }
         return validationResult;
     }
 }
index 0f68882..500c5a8 100644 (file)
@@ -36,6 +36,8 @@ import io.swagger.annotations.Info;
 import io.swagger.annotations.ResponseHeader;\r
 import io.swagger.annotations.SecurityDefinition;\r
 import io.swagger.annotations.SwaggerDefinition;\r
+import java.util.List;\r
+import java.util.Map;\r
 import java.util.UUID;\r
 import javax.ws.rs.Consumes;\r
 import javax.ws.rs.DELETE;\r
@@ -45,15 +47,18 @@ import javax.ws.rs.POST;
 import javax.ws.rs.Path;\r
 import javax.ws.rs.PathParam;\r
 import javax.ws.rs.Produces;\r
-import javax.ws.rs.QueryParam;\r
 import javax.ws.rs.core.Response;\r
 import javax.ws.rs.core.Response.ResponseBuilder;\r
+import org.apache.commons.lang3.tuple.Pair;\r
 import org.onap.policy.api.main.rest.provider.HealthCheckProvider;\r
 import org.onap.policy.api.main.rest.provider.PolicyProvider;\r
 import org.onap.policy.api.main.rest.provider.PolicyTypeProvider;\r
 import org.onap.policy.api.main.rest.provider.StatisticsProvider;\r
 import org.onap.policy.common.endpoints.report.HealthCheckReport;\r
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;\r
+import org.onap.policy.models.base.PfModelException;\r
+import org.onap.policy.models.base.PfModelRuntimeException;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
 \r
 /**\r
  * Class to provide REST API services.\r
@@ -126,6 +131,8 @@ public class ApiRestController {
         })\r
     public Response getHealthCheck(\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
+\r
+        updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);\r
         return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
             .entity(new HealthCheckProvider().performHealthCheck()).build();\r
     }\r
@@ -172,6 +179,8 @@ public class ApiRestController {
         })\r
     public Response getStatistics(\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
+\r
+        updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);\r
         return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
             .entity(new StatisticsProvider().fetchCurrentStatistics()).build();\r
     }\r
@@ -218,8 +227,18 @@ public class ApiRestController {
         })\r
     public Response getAllPolicyTypes(\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyTypeProvider().fetchPolicyTypes(null, null)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider().fetchPolicyTypes(null, null);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
@@ -268,8 +287,19 @@ public class ApiRestController {
     public Response getAllVersionsOfPolicyType(\r
             @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyTypeProvider().fetchPolicyTypes(policyTypeId, null)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()\r
+                    .fetchPolicyTypes(policyTypeId, null);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
@@ -320,8 +350,19 @@ public class ApiRestController {
             @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
             @PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyTypeProvider().fetchPolicyTypes(policyTypeId, versionId)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()\r
+                    .fetchPolicyTypes(policyTypeId, versionId);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
@@ -370,33 +411,37 @@ public class ApiRestController {
     public Response createPolicyType(\r
             @ApiParam(value = "Entity body of policy type", required = true) ToscaServiceTemplate body,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyTypeProvider().createPolicyType(body)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider().createPolicyType(body);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.POST);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.POST);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
-     * Deletes all versions of a particular policy type.\r
+     * Deletes specified version of a particular policy type.\r
      *\r
      * @param policyTypeId the ID of specified policy type\r
+     * @param versionId the version of specified policy type\r
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
     @DELETE\r
-    @Path("/policytypes/{policyTypeId}")\r
-    @ApiOperation(value = "Delete all versions of a policy type",\r
+    @Path("/policytypes/{policyTypeId}/versions/{versionId}")\r
+    @ApiOperation(value = "Delete one version of a policy type",\r
             notes = "Rule 1: pre-defined policy types cannot be deleted;"\r
                   + "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted."\r
                   + "The parameterizing TOSCA policies must be deleted first;",\r
             authorizations = @Authorization(value = "basicAuth"),\r
             tags = { "PolicyType", },\r
-            extensions = {\r
-                    @Extension(name = "interface info", properties = {\r
-                            @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
-                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
-                    })\r
-            })\r
-    @ApiResponses(value = {\r
-            @ApiResponse(code = 204, message = "Resources successfully deleted, no content returned",\r
+            response = ToscaServiceTemplate.class,\r
             responseHeaders = {\r
                     @ResponseHeader(name = "X-MinorVersion",\r
                                     description = "Used to request or communicate a MINOR version back from the client"\r
@@ -413,36 +458,7 @@ public class ApiRestController {
                     @ResponseHeader(name = "X-ONAP-RequestID",\r
                                     description = "Used to track REST transactions for logging purpose",\r
                                     response = UUID.class)\r
-            }),\r
-            @ApiResponse(code = 401, message = "Authentication Error"),\r
-            @ApiResponse(code = 403, message = "Authorization Error"),\r
-            @ApiResponse(code = 404, message = "Resource Not Found"),\r
-            @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"),\r
-            @ApiResponse(code = 500, message = "Internal Server Error")\r
-        })\r
-    public Response deleteAllVersionsOfPolicyType(\r
-            @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyTypeProvider().deletePolicyTypes(policyTypeId, null)).build();\r
-    }\r
-\r
-    /**\r
-     * Deletes specified version of a particular policy type.\r
-     *\r
-     * @param policyTypeId the ID of specified policy type\r
-     * @param versionId the version of specified policy type\r
-     *\r
-     * @return the Response object containing the results of the API operation\r
-     */\r
-    @DELETE\r
-    @Path("/policytypes/{policyTypeId}/versions/{versionId}")\r
-    @ApiOperation(value = "Delete one version of a policy type",\r
-            notes = "Rule 1: pre-defined policy types cannot be deleted;"\r
-                  + "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted."\r
-                  + "The parameterizing TOSCA policies must be deleted first;",\r
-            authorizations = @Authorization(value = "basicAuth"),\r
-            tags = { "PolicyType", },\r
+            },\r
             extensions = {\r
                     @Extension(name = "interface info", properties = {\r
                             @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
@@ -450,24 +466,6 @@ public class ApiRestController {
                     })\r
             })\r
     @ApiResponses(value = {\r
-            @ApiResponse(code = 204, message = "Resource successfully deleted, no content returned",\r
-            responseHeaders = {\r
-                    @ResponseHeader(name = "X-MinorVersion",\r
-                                    description = "Used to request or communicate a MINOR version back from the client"\r
-                                                + " to the server, and from the server back to the client",\r
-                                    response = String.class),\r
-                    @ResponseHeader(name = "X-PatchVersion",\r
-                                    description = "Used only to communicate a PATCH version in a response for"\r
-                                                + " troubleshooting purposes only, and will not be provided by"\r
-                                                + " the client on request",\r
-                                    response = String.class),\r
-                    @ResponseHeader(name = "X-LatestVersion",\r
-                                    description = "Used only to communicate an API's latest version",\r
-                                    response = String.class),\r
-                    @ResponseHeader(name = "X-ONAP-RequestID",\r
-                                    description = "Used to track REST transactions for logging purpose",\r
-                                    response = UUID.class)\r
-            }),\r
             @ApiResponse(code = 401, message = "Authentication Error"),\r
             @ApiResponse(code = 403, message = "Authorization Error"),\r
             @ApiResponse(code = 404, message = "Resource Not Found"),\r
@@ -478,8 +476,17 @@ public class ApiRestController {
             @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
             @PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyTypeProvider().deletePolicyTypes(policyTypeId, versionId)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()\r
+                    .deletePolicyType(policyTypeId, versionId);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
@@ -531,8 +538,19 @@ public class ApiRestController {
             @PathParam("policyTypeVersion")\r
                 @ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, null, null)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+                    .fetchPolicies(policyTypeId, policyTypeVersion, null, null);\r
+            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
@@ -586,8 +604,19 @@ public class ApiRestController {
                 @ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, policyId, null)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+                    .fetchPolicies(policyTypeId, policyTypeVersion, policyId, null);\r
+            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
@@ -643,13 +672,23 @@ public class ApiRestController {
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
             @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion,\r
-                                                       policyId, policyVersion)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+                    .fetchPolicies(policyTypeId, policyTypeVersion, policyId, policyVersion);\r
+            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
-     * Retrieves either latest or deployed version of a particular policy depending on query parameter.\r
+     * Retrieves the latest version of a particular policy.\r
      *\r
      * @param policyTypeId the ID of specified policy type\r
      * @param policyTypeVersion the version of specified policy type\r
@@ -658,9 +697,9 @@ public class ApiRestController {
      * @return the Response object containing the results of the API operation\r
      */\r
     @GET\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions")\r
-    @ApiOperation(value = "Retrieve either latest or deployed version of a particular policy depending on query param",\r
-            notes = "Returns either latest or deployed version of specified policy depending on query param",\r
+    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/latest")\r
+    @ApiOperation(value = "Retrieve the latest version of a particular policy",\r
+            notes = "Returns the latest version of specified policy",\r
             response = ToscaServiceTemplate.class,\r
             responseHeaders = {\r
                     @ResponseHeader(name = "X-MinorVersion",\r
@@ -693,34 +732,41 @@ public class ApiRestController {
             @ApiResponse(code = 404, message = "Resource Not Found"),\r
             @ApiResponse(code = 500, message = "Internal Server Error")\r
         })\r
-    public Response getEitherLatestOrDeployedVersionOfPolicy(\r
+    public Response getLatestVersionOfPolicy(\r
             @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
             @PathParam("policyTypeVersion")\r
                 @ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
-            @QueryParam("type")\r
-                @ApiParam(value = "Version that can only be 'latest' or 'deployed'", required = true) String type,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, policyId, type)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate =\r
+                    new PolicyProvider().fetchLatestPolicies(policyTypeId, policyTypeVersion, policyId);\r
+            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
-     * Creates a new policy for a particular policy type and version.\r
+     * Retrieves deployed versions of a particular policy in pdp groups.\r
      *\r
      * @param policyTypeId the ID of specified policy type\r
      * @param policyTypeVersion the version of specified policy type\r
-     * @param body the body of policy following TOSCA definition\r
+     * @param policyId the ID of specified policy\r
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @POST\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")\r
-    @ApiOperation(value = "Create a new policy for a policy type version",\r
-            notes = "Client should provide TOSCA body of the new policy",\r
-            authorizations = @Authorization(value = "basicAuth"),\r
-            tags = { "Policy", },\r
-            response = ToscaServiceTemplate.class,\r
+    @GET\r
+    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/deployed")\r
+    @ApiOperation(value = "Retrieve deployed versions of a particular policy in pdp groups",\r
+            notes = "Returns deployed versions of specified policy in pdp groups",\r
+            response = ToscaPolicy.class, responseContainer = "List",\r
             responseHeaders = {\r
                     @ResponseHeader(name = "X-MinorVersion",\r
                                     description = "Used to request or communicate a MINOR version back from the client"\r
@@ -738,6 +784,8 @@ public class ApiRestController {
                                     description = "Used to track REST transactions for logging purpose",\r
                                     response = UUID.class)\r
             },\r
+            authorizations = @Authorization(value = "basicAuth"),\r
+            tags = { "Policy", },\r
             extensions = {\r
                     @Extension(name = "interface info", properties = {\r
                             @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
@@ -745,45 +793,48 @@ public class ApiRestController {
                     })\r
             })\r
     @ApiResponses(value = {\r
-            @ApiResponse(code = 400, message = "Invalid Body"),\r
             @ApiResponse(code = 401, message = "Authentication Error"),\r
             @ApiResponse(code = 403, message = "Authorization Error"),\r
             @ApiResponse(code = 404, message = "Resource Not Found"),\r
             @ApiResponse(code = 500, message = "Internal Server Error")\r
         })\r
-    public Response createPolicy(\r
+    public Response getDeployedVersionsOfPolicy(\r
             @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
             @PathParam("policyTypeVersion")\r
                 @ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
-            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,\r
-            @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyProvider().createPolicy(policyTypeId, policyTypeVersion, body)).build();\r
+            @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
+            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
+\r
+        try {\r
+            Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = new PolicyProvider()\r
+                    .fetchDeployedPolicies(policyTypeId, policyTypeVersion, policyId);\r
+            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(deployedPolicies).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
-     * Deletes all versions of a particular policy.\r
+     * Creates a new policy for a particular policy type and version.\r
      *\r
      * @param policyTypeId the ID of specified policy type\r
      * @param policyTypeVersion the version of specified policy type\r
-     * @param policyId the ID of specified policy\r
+     * @param body the body of policy following TOSCA definition\r
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @DELETE\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}")\r
-    @ApiOperation(value = "Delete all versions of a policy",\r
-            notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",\r
+    @POST\r
+    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")\r
+    @ApiOperation(value = "Create a new policy for a policy type version",\r
+            notes = "Client should provide TOSCA body of the new policy",\r
             authorizations = @Authorization(value = "basicAuth"),\r
             tags = { "Policy", },\r
-            extensions = {\r
-                    @Extension(name = "interface info", properties = {\r
-                            @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
-                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
-                    })\r
-            })\r
-    @ApiResponses(value = {\r
-            @ApiResponse(code = 204, message = "Resources successfully deleted, no content returned",\r
+            response = ToscaServiceTemplate.class,\r
             responseHeaders = {\r
                     @ResponseHeader(name = "X-MinorVersion",\r
                                     description = "Used to request or communicate a MINOR version back from the client"\r
@@ -800,21 +851,39 @@ public class ApiRestController {
                     @ResponseHeader(name = "X-ONAP-RequestID",\r
                                     description = "Used to track REST transactions for logging purpose",\r
                                     response = UUID.class)\r
-            }),\r
+            },\r
+            extensions = {\r
+                    @Extension(name = "interface info", properties = {\r
+                            @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
+                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
+                    })\r
+            })\r
+    @ApiResponses(value = {\r
+            @ApiResponse(code = 400, message = "Invalid Body"),\r
             @ApiResponse(code = 401, message = "Authentication Error"),\r
             @ApiResponse(code = 403, message = "Authorization Error"),\r
             @ApiResponse(code = 404, message = "Resource Not Found"),\r
-            @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"),\r
             @ApiResponse(code = 500, message = "Internal Server Error")\r
         })\r
-    public Response deleteAllVersionsOfPolicy(\r
+    public Response createPolicy(\r
             @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
             @PathParam("policyTypeVersion")\r
                 @ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
-            @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
-            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyProvider().deletePolicies(policyTypeId, policyTypeVersion, policyId, null)).build();\r
+            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,\r
+            @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+                    .createPolicy(policyTypeId, policyTypeVersion, body);\r
+            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.POST);\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     /**\r
@@ -833,14 +902,7 @@ public class ApiRestController {
             notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",\r
             authorizations = @Authorization(value = "basicAuth"),\r
             tags = { "Policy", },\r
-            extensions = {\r
-                    @Extension(name = "interface info", properties = {\r
-                            @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
-                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
-                    })\r
-            })\r
-    @ApiResponses(value = {\r
-            @ApiResponse(code = 204, message = "Resource successfully deleted, no content returned",\r
+            response = ToscaServiceTemplate.class,\r
             responseHeaders = {\r
                     @ResponseHeader(name = "X-MinorVersion",\r
                                     description = "Used to request or communicate a MINOR version back from the client"\r
@@ -857,7 +919,14 @@ public class ApiRestController {
                     @ResponseHeader(name = "X-ONAP-RequestID",\r
                                     description = "Used to track REST transactions for logging purpose",\r
                                     response = UUID.class)\r
-            }),\r
+            },\r
+            extensions = {\r
+                    @Extension(name = "interface info", properties = {\r
+                            @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
+                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
+                    })\r
+            })\r
+    @ApiResponses(value = {\r
             @ApiResponse(code = 401, message = "Authentication Error"),\r
             @ApiResponse(code = 403, message = "Authorization Error"),\r
             @ApiResponse(code = 404, message = "Resource Not Found"),\r
@@ -871,9 +940,17 @@ public class ApiRestController {
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
             @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-            .entity(new PolicyProvider().deletePolicies(policyTypeId, policyTypeVersion,\r
-                                                        policyId, policyVersion)).build();\r
+\r
+        try {\r
+            ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+                    .deletePolicy(policyTypeId, policyTypeVersion, policyId, policyVersion);\r
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+                    .entity(serviceTemplate).build();\r
+        } catch (PfModelException | PfModelRuntimeException pfme) {\r
+            return addLoggingHeaders(addVersionControlHeaders(\r
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+                    .entity(pfme.getErrorResponse()).build();\r
+        }\r
     }\r
 \r
     private ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {\r
@@ -887,4 +964,68 @@ public class ApiRestController {
         }\r
         return rb.header("X-ONAP-RequestID", requestId);\r
     }\r
+\r
+    private enum Target {\r
+        POLICY, POLICY_TYPE, OTHER\r
+    }\r
+\r
+    private enum Result {\r
+        SUCCESS, FAILURE\r
+    }\r
+\r
+    private enum HttpMethod {\r
+        POST, GET\r
+    }\r
+\r
+    private void updateApiStatisticsCounter(Target target, Result result, HttpMethod http) {\r
+\r
+        ApiStatisticsManager.updateTotalApiCallCount();\r
+        if (target == Target.POLICY) {\r
+            if (result == Result.SUCCESS) {\r
+                if (http == HttpMethod.GET) {\r
+                    ApiStatisticsManager.updateApiCallSuccessCount();\r
+                    ApiStatisticsManager.updateTotalPolicyGetCount();\r
+                    ApiStatisticsManager.updatePolicyGetSuccessCount();\r
+                } else if (http == HttpMethod.POST) {\r
+                    ApiStatisticsManager.updateApiCallSuccessCount();\r
+                    ApiStatisticsManager.updateTotalPolicyPostCount();\r
+                    ApiStatisticsManager.updatePolicyPostSuccessCount();\r
+                }\r
+            } else {\r
+                if (http == HttpMethod.GET) {\r
+                    ApiStatisticsManager.updateApiCallFailureCount();\r
+                    ApiStatisticsManager.updateTotalPolicyGetCount();\r
+                    ApiStatisticsManager.updatePolicyGetFailureCount();\r
+                } else {\r
+                    ApiStatisticsManager.updateApiCallFailureCount();\r
+                    ApiStatisticsManager.updateTotalPolicyPostCount();\r
+                    ApiStatisticsManager.updatePolicyPostFailureCount();\r
+                }\r
+            }\r
+        } else if (target == Target.POLICY_TYPE) {\r
+            if (result == Result.SUCCESS) {\r
+                if (http == HttpMethod.GET) {\r
+                    ApiStatisticsManager.updateApiCallSuccessCount();\r
+                    ApiStatisticsManager.updateTotalPolicyTypeGetCount();\r
+                    ApiStatisticsManager.updatePolicyTypeGetSuccessCount();\r
+                } else if (http == HttpMethod.POST) {\r
+                    ApiStatisticsManager.updateApiCallSuccessCount();\r
+                    ApiStatisticsManager.updatePolicyTypePostSuccessCount();\r
+                    ApiStatisticsManager.updatePolicyTypePostSuccessCount();\r
+                }\r
+            } else {\r
+                if (http == HttpMethod.GET) {\r
+                    ApiStatisticsManager.updateApiCallFailureCount();\r
+                    ApiStatisticsManager.updateTotalPolicyTypeGetCount();\r
+                    ApiStatisticsManager.updatePolicyTypeGetFailureCount();\r
+                } else {\r
+                    ApiStatisticsManager.updateApiCallFailureCount();\r
+                    ApiStatisticsManager.updateTotalPolicyTypePostCount();\r
+                    ApiStatisticsManager.updatePolicyTypePostFailureCount();\r
+                }\r
+            }\r
+        } else {\r
+            ApiStatisticsManager.updateApiCallSuccessCount();\r
+        }\r
+    }\r
 }
\ No newline at end of file
index 46ec34d..2a7b0ce 100644 (file)
@@ -31,7 +31,7 @@ import org.onap.policy.api.main.rest.aaf.AafApiFilter;
 import org.onap.policy.common.capabilities.Startable;
 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
-import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler;
+import org.onap.policy.common.gson.GsonMessageBodyHandler;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -105,7 +105,7 @@ public class ApiRestServer implements Startable {
         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX,
                         String.valueOf(restServerParameters.isAaf()));
         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
-                        ToscaServiceTemplateMessageBodyHandler.class.getName());
+                        GsonMessageBodyHandler.class.getName());
 
         return props;
     }
index 8e00b43..38736e8 100644 (file)
@@ -31,6 +31,7 @@ import io.swagger.annotations.Authorization;
 import io.swagger.annotations.Extension;
 import io.swagger.annotations.ExtensionProperty;
 import io.swagger.annotations.ResponseHeader;
+import java.util.Map;
 import java.util.UUID;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
@@ -44,9 +45,11 @@ import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.ResponseBuilder;
 import org.onap.policy.api.main.rest.provider.LegacyGuardPolicyProvider;
 import org.onap.policy.api.main.rest.provider.LegacyOperationalPolicyProvider;
-import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.base.PfModelRuntimeException;
+import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
+import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
 
 /**
  * Class to provide legacy REST API services.
@@ -69,7 +72,7 @@ public class LegacyApiRestController {
     @Produces("application/json; vnd.onap.guard")
     @ApiOperation(value = "Retrieve all versions of guard policies",
             notes = "Returns a list of all versions of guard policies",
-            response = ToscaServiceTemplate.class,
+            response = LegacyGuardPolicyOutput.class, responseContainer = "Map",
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -102,8 +105,17 @@ public class LegacyApiRestController {
         })
     public Response getAllGuardPolicies(
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyGuardPolicyProvider().fetchGuardPolicies(null, null)).build();
+
+        try {
+            Map<String, LegacyGuardPolicyOutput> policies = new LegacyGuardPolicyProvider()
+                    .fetchGuardPolicies(null, null);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policies).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
@@ -118,7 +130,7 @@ public class LegacyApiRestController {
     @Produces("application/json; vnd.onap.guard")
     @ApiOperation(value = "Retrieve all versions of a particular guard policy",
             notes = "Returns a list of all versions of the specified guard policy",
-            response = ToscaServiceTemplate.class,
+            response = LegacyGuardPolicyOutput.class, responseContainer = "Map",
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -153,8 +165,17 @@ public class LegacyApiRestController {
     public Response getAllVersionsOfGuardPolicy(
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyGuardPolicyProvider().fetchGuardPolicies(policyId, null)).build();
+
+        try {
+            Map<String, LegacyGuardPolicyOutput> policies = new LegacyGuardPolicyProvider()
+                    .fetchGuardPolicies(policyId, null);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policies).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
@@ -170,7 +191,7 @@ public class LegacyApiRestController {
     @Produces("application/json; vnd.onap.guard")
     @ApiOperation(value = "Retrieve one version of a particular guard policy",
             notes = "Returns a particular version of a specified guard policy",
-            response = ToscaServiceTemplate.class,
+            response = LegacyGuardPolicyOutput.class, responseContainer = "Map",
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -206,8 +227,17 @@ public class LegacyApiRestController {
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
             @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyGuardPolicyProvider().fetchGuardPolicies(policyId, policyVersion)).build();
+
+        try {
+            Map<String, LegacyGuardPolicyOutput> policies = new LegacyGuardPolicyProvider()
+                    .fetchGuardPolicies(policyId, policyVersion);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policies).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
@@ -225,7 +255,7 @@ public class LegacyApiRestController {
             notes = "Client should provide entity body of the new guard policy",
             authorizations = @Authorization(value = "basicAuth"),
             tags = { "Legacy Guard Policy", },
-            response = ToscaServiceTemplate.class,
+            response = LegacyGuardPolicyOutput.class, responseContainer = "Map",
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -257,32 +287,35 @@ public class LegacyApiRestController {
         })
     public Response createGuardPolicy(
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,
-            @ApiParam(value = "Entity body of policy", required = true) LegacyGuardPolicy body) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyGuardPolicyProvider().createGuardPolicy(body)).build();
+            @ApiParam(value = "Entity body of policy", required = true) LegacyGuardPolicyInput body) {
+
+        try {
+            Map<String, LegacyGuardPolicyOutput> policy = new LegacyGuardPolicyProvider().createGuardPolicy(body);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policy).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
-     * Deletes all versions of a particular guard policy.
+     * Deletes the specified version of a particular guard policy.
      *
      * @param policyId the ID of specified policy
+     * @param policyVersion the version of specified policy
      *
      * @return the Response object containing the results of the API operation
      */
     @DELETE
-    @Path("/policytypes/onap.policy.controlloop.guard/versions/1.0.0/policies/{policyId}")
-    @ApiOperation(value = "Delete all versions of a guard policy",
+    @Path("/policytypes/onap.policy.controlloop.guard/versions/1.0.0/policies/{policyId}/versions/{policyVersion}")
+    @Produces("application/json; vnd.onap.guard")
+    @ApiOperation(value = "Delete a particular version of a guard policy",
             notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",
             authorizations = @Authorization(value = "basicAuth"),
             tags = { "Legacy Guard Policy", },
-            extensions = {
-                    @Extension(name = "interface info", properties = {
-                            @ExtensionProperty(name = "api-version", value = "1.0.0"),
-                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")
-                    })
-            })
-    @ApiResponses(value = {
-            @ApiResponse(code = 204, message = "Resources successfully deleted, no content returned",
+            response = LegacyGuardPolicyOutput.class, responseContainer = "Map",
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -299,34 +332,7 @@ public class LegacyApiRestController {
                     @ResponseHeader(name = "X-ONAP-RequestID",
                                     description = "Used to track REST transactions for logging purpose",
                                     response = UUID.class)
-            }),
-            @ApiResponse(code = 401, message = "Authentication Error"),
-            @ApiResponse(code = 403, message = "Authorization Error"),
-            @ApiResponse(code = 404, message = "Resource Not Found"),
-            @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"),
-            @ApiResponse(code = 500, message = "Internal Server Error")
-        })
-    public Response deleteAllVersionsOfGuardPolicy(
-            @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
-            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyGuardPolicyProvider().deleteGuardPolicies(policyId, null)).build();
-    }
-
-    /**
-     * Deletes the specified version of a particular guard policy.
-     *
-     * @param policyId the ID of specified policy
-     * @param policyVersion the version of specified policy
-     *
-     * @return the Response object containing the results of the API operation
-     */
-    @DELETE
-    @Path("/policytypes/onap.policy.controlloop.guard/versions/1.0.0/policies/{policyId}/versions/{policyVersion}")
-    @ApiOperation(value = "Delete a particular version of a guard policy",
-            notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",
-            authorizations = @Authorization(value = "basicAuth"),
-            tags = { "Legacy Guard Policy", },
+            },
             extensions = {
                     @Extension(name = "interface info", properties = {
                             @ExtensionProperty(name = "api-version", value = "1.0.0"),
@@ -334,24 +340,6 @@ public class LegacyApiRestController {
                     })
             })
     @ApiResponses(value = {
-            @ApiResponse(code = 204, message = "Resource successfully deleted, no content returned",
-            responseHeaders = {
-                    @ResponseHeader(name = "X-MinorVersion",
-                                    description = "Used to request or communicate a MINOR version back from the client"
-                                                + " to the server, and from the server back to the client",
-                                    response = String.class),
-                    @ResponseHeader(name = "X-PatchVersion",
-                                    description = "Used only to communicate a PATCH version in a response for"
-                                                + " troubleshooting purposes only, and will not be provided by"
-                                                + " the client on request",
-                                    response = String.class),
-                    @ResponseHeader(name = "X-LatestVersion",
-                                    description = "Used only to communicate an API's latest version",
-                                    response = String.class),
-                    @ResponseHeader(name = "X-ONAP-RequestID",
-                                    description = "Used to track REST transactions for logging purpose",
-                                    response = UUID.class)
-            }),
             @ApiResponse(code = 401, message = "Authentication Error"),
             @ApiResponse(code = 403, message = "Authorization Error"),
             @ApiResponse(code = 404, message = "Resource Not Found"),
@@ -362,8 +350,17 @@ public class LegacyApiRestController {
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
             @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyGuardPolicyProvider().deleteGuardPolicies(policyId, policyVersion)).build();
+
+        try {
+            Map<String, LegacyGuardPolicyOutput> policies = new LegacyGuardPolicyProvider()
+                    .deleteGuardPolicies(policyId, policyVersion);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policies).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
@@ -376,7 +373,7 @@ public class LegacyApiRestController {
     @Produces("application/json; vnd.onap.operational")
     @ApiOperation(value = "Retrieve all versions of operational policies",
             notes = "Returns a list of all versions of operational policies",
-            response = ToscaServiceTemplate.class,
+            response = LegacyOperationalPolicy.class,
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -409,8 +406,17 @@ public class LegacyApiRestController {
         })
     public Response getAllOperationalPolicies(
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyOperationalPolicyProvider().fetchOperationalPolicies(null, null)).build();
+
+        try {
+            LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider()
+                    .fetchOperationalPolicies(null, null);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policy).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
@@ -425,7 +431,7 @@ public class LegacyApiRestController {
     @Produces("application/json; vnd.onap.operational")
     @ApiOperation(value = "Retrieve all versions of a particular operational policy",
             notes = "Returns a list of all versions of the specified operational policy",
-            response = ToscaServiceTemplate.class,
+            response = LegacyOperationalPolicy.class,
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -460,8 +466,17 @@ public class LegacyApiRestController {
     public Response getAllVersionsOfOperationalPolicy(
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyOperationalPolicyProvider().fetchOperationalPolicies(policyId, null)).build();
+
+        try {
+            LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider()
+                    .fetchOperationalPolicies(policyId, null);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policy).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
@@ -478,7 +493,7 @@ public class LegacyApiRestController {
     @Produces("application/json; vnd.onap.operational")
     @ApiOperation(value = "Retrieve one version of a particular operational policy",
             notes = "Returns a particular version of a specified operational policy",
-            response = ToscaServiceTemplate.class,
+            response = LegacyOperationalPolicy.class,
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -514,8 +529,17 @@ public class LegacyApiRestController {
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
             @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyOperationalPolicyProvider().fetchOperationalPolicies(policyId, policyVersion)).build();
+
+        try {
+            LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider()
+                    .fetchOperationalPolicies(policyId, policyVersion);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policy).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
@@ -533,7 +557,7 @@ public class LegacyApiRestController {
             notes = "Client should provide entity body of the new operational policy",
             authorizations = @Authorization(value = "basicAuth"),
             tags = { "Legacy Operational Policy", },
-            response = ToscaServiceTemplate.class,
+            response = LegacyOperationalPolicy.class,
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -566,31 +590,36 @@ public class LegacyApiRestController {
     public Response createOperationalPolicy(
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,
             @ApiParam(value = "Entity body of policy", required = true) LegacyOperationalPolicy body) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyOperationalPolicyProvider().createOperationalPolicy(body)).build();
+
+        try {
+            LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider()
+                    .createOperationalPolicy(body);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policy).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     /**
-     * Deletes all versions of a particular operational policy.
+     * Deletes the specified version of a particular operational policy.
      *
      * @param policyId the ID of specified policy
+     * @param policyVersion the version of specified policy
      *
      * @return the Response object containing the results of the API operation
      */
     @DELETE
-    @Path("/policytypes/onap.policy.controlloop.operational/versions/1.0.0/policies/{policyId}")
-    @ApiOperation(value = "Delete all versions of a operational policy",
+    @Path("/policytypes/onap.policy.controlloop.operational/versions/1.0.0/"
+         + "policies/{policyId}/versions/{policyVersion}")
+    @Produces("application/json; vnd.onap.operational")
+    @ApiOperation(value = "Delete a particular version of a specified operational policy",
             notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",
             authorizations = @Authorization(value = "basicAuth"),
             tags = { "Legacy Operational Policy", },
-            extensions = {
-                    @Extension(name = "interface info", properties = {
-                            @ExtensionProperty(name = "api-version", value = "1.0.0"),
-                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")
-                    })
-            })
-    @ApiResponses(value = {
-            @ApiResponse(code = 204, message = "Resources successfully deleted, no content returned",
+            response = LegacyOperationalPolicy.class,
             responseHeaders = {
                     @ResponseHeader(name = "X-MinorVersion",
                                     description = "Used to request or communicate a MINOR version back from the client"
@@ -607,35 +636,7 @@ public class LegacyApiRestController {
                     @ResponseHeader(name = "X-ONAP-RequestID",
                                     description = "Used to track REST transactions for logging purpose",
                                     response = UUID.class)
-            }),
-            @ApiResponse(code = 401, message = "Authentication Error"),
-            @ApiResponse(code = 403, message = "Authorization Error"),
-            @ApiResponse(code = 404, message = "Resource Not Found"),
-            @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"),
-            @ApiResponse(code = 500, message = "Internal Server Error")
-        })
-    public Response deleteAllVersionsOfOperationalPolicy(
-            @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
-            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyOperationalPolicyProvider().deleteOperationalPolicies(policyId, null)).build();
-    }
-
-    /**
-     * Deletes the specified version of a particular operational policy.
-     *
-     * @param policyId the ID of specified policy
-     * @param policyVersion the version of specified policy
-     *
-     * @return the Response object containing the results of the API operation
-     */
-    @DELETE
-    @Path("/policytypes/onap.policy.controlloop.operational/versions/1.0.0/"
-         + "policies/{policyId}/versions/{policyVersion}")
-    @ApiOperation(value = "Delete a particular version of a specified operational policy",
-            notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",
-            authorizations = @Authorization(value = "basicAuth"),
-            tags = { "Legacy Operational Policy", },
+            },
             extensions = {
                     @Extension(name = "interface info", properties = {
                             @ExtensionProperty(name = "api-version", value = "1.0.0"),
@@ -643,24 +644,6 @@ public class LegacyApiRestController {
                     })
             })
     @ApiResponses(value = {
-            @ApiResponse(code = 204, message = "Resource successfully deleted, no content returned",
-            responseHeaders = {
-                    @ResponseHeader(name = "X-MinorVersion",
-                                    description = "Used to request or communicate a MINOR version back from the client"
-                                                + " to the server, and from the server back to the client",
-                                    response = String.class),
-                    @ResponseHeader(name = "X-PatchVersion",
-                                    description = "Used only to communicate a PATCH version in a response for"
-                                                + " troubleshooting purposes only, and will not be provided by"
-                                                + " the client on request",
-                                    response = String.class),
-                    @ResponseHeader(name = "X-LatestVersion",
-                                    description = "Used only to communicate an API's latest version",
-                                    response = String.class),
-                    @ResponseHeader(name = "X-ONAP-RequestID",
-                                    description = "Used to track REST transactions for logging purpose",
-                                    response = UUID.class)
-            }),
             @ApiResponse(code = 401, message = "Authentication Error"),
             @ApiResponse(code = 403, message = "Authorization Error"),
             @ApiResponse(code = 404, message = "Resource Not Found"),
@@ -671,8 +654,17 @@ public class LegacyApiRestController {
             @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
             @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
             @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
-            .entity(new LegacyOperationalPolicyProvider().deleteOperationalPolicies(policyId, policyVersion)).build();
+
+        try {
+            LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider()
+                    .deleteOperationalPolicies(policyId, policyVersion);
+            return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+                    .entity(policy).build();
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            return addLoggingHeaders(addVersionControlHeaders(
+                    Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+                    .entity(pfme.getErrorResponse()).build();
+        }
     }
 
     private ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {
index f627493..60d1b1f 100644 (file)
 
 package org.onap.policy.api.main.rest.provider;
 
-import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy;
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
+import java.util.Map;
+import javax.ws.rs.core.Response;
+import org.onap.policy.api.main.parameters.ApiParameterGroup;
+import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
+import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
+import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
 
 /**
  * Class to provide all kinds of legacy guard policy operations.
@@ -32,7 +40,18 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
  */
 public class LegacyGuardPolicyProvider {
 
-    private static final String DELETE_OK = "Successfully deleted";
+    private PolicyModelsProvider modelsProvider;
+
+    /**
+     * Default constructor.
+     */
+    public LegacyGuardPolicyProvider() throws PfModelException {
+
+        ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
+        PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
+        modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+        modelsProvider.init();
+    }
 
     /**
      * Retrieves a list of guard policies matching specified ID and version.
@@ -40,11 +59,14 @@ public class LegacyGuardPolicyProvider {
      * @param policyId the ID of policy
      * @param policyVersion the version of policy
      *
-     * @return the ToscaServiceTemplate object
+     * @return the map of LegacyGuardPolicyOutput objects
      */
-    public ToscaServiceTemplate fetchGuardPolicies(String policyId, String policyVersion) {
-        // placeholder
-        return new ToscaServiceTemplate();
+    public Map<String, LegacyGuardPolicyOutput> fetchGuardPolicies(String policyId, String policyVersion)
+            throws PfModelException {
+
+        Map<String, LegacyGuardPolicyOutput> guardPolicies = modelsProvider.getGuardPolicy(policyId);
+        close();
+        return guardPolicies;
     }
 
     /**
@@ -52,11 +74,12 @@ public class LegacyGuardPolicyProvider {
      *
      * @param body the entity body of policy
      *
-     * @return the ToscaServiceTemplate object
+     * @return the map of LegacyGuardPolicyOutput objectst
      */
-    public ToscaServiceTemplate createGuardPolicy(LegacyGuardPolicy body) {
-        // placeholder
-        return new ToscaServiceTemplate();
+    public Map<String, LegacyGuardPolicyOutput> createGuardPolicy(LegacyGuardPolicyInput body) throws PfModelException {
+        Map<String, LegacyGuardPolicyOutput> guardPolicies = modelsProvider.createGuardPolicy(body);
+        close();
+        return guardPolicies;
     }
 
     /**
@@ -65,10 +88,27 @@ public class LegacyGuardPolicyProvider {
      * @param policyId the ID of policy
      * @param policyVersion the version of policy
      *
-     * @return a string message indicating the operation results
+     * @return the map of LegacyGuardPolicyOutput objects
+     */
+    public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicies(String policyId, String policyVersion)
+            throws PfModelException {
+
+        Map<String, LegacyGuardPolicyOutput> guardPolicies = modelsProvider.deleteGuardPolicy(policyId);
+        close();
+        return guardPolicies;
+    }
+
+    /**
+     * Closes the connection to database.
+     *
+     * @throws PfModelException the PfModel parsing exception
      */
-    public String deleteGuardPolicies(String policyId, String policyVersion) {
-        // placeholder
-        return DELETE_OK;
+    private void close() throws PfModelException {
+        try {
+            modelsProvider.close();
+        } catch (Exception e) {
+            throw new PfModelException(
+                    Response.Status.INTERNAL_SERVER_ERROR, "error closing connection to database", e);
+        }
     }
 }
\ No newline at end of file
index 7d3e187..2f0b127 100644 (file)
 
 package org.onap.policy.api.main.rest.provider;
 
+import javax.ws.rs.core.Response;
+import org.onap.policy.api.main.parameters.ApiParameterGroup;
+import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
 
 /**
  * Class to provide all kinds of legacy operational policy operations.
@@ -32,7 +38,18 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
  */
 public class LegacyOperationalPolicyProvider {
 
-    private static final String DELETE_OK = "Successfully deleted";
+    private PolicyModelsProvider modelsProvider;
+
+    /**
+     * Default constructor.
+     */
+    public LegacyOperationalPolicyProvider() throws PfModelException {
+
+        ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
+        PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
+        modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+        modelsProvider.init();
+    }
 
     /**
      * Retrieves a list of operational policies matching specified ID and version.
@@ -40,11 +57,14 @@ public class LegacyOperationalPolicyProvider {
      * @param policyId the ID of policy
      * @param policyVersion the version of policy
      *
-     * @return the ToscaServiceTemplate object
+     * @return the LegacyOperationalPolicy object
      */
-    public ToscaServiceTemplate fetchOperationalPolicies(String policyId, String policyVersion) {
-        // placeholder
-        return new ToscaServiceTemplate();
+    public LegacyOperationalPolicy fetchOperationalPolicies(String policyId, String policyVersion)
+            throws PfModelException {
+
+        LegacyOperationalPolicy operationalPolicy = modelsProvider.getOperationalPolicy(policyId);
+        close();
+        return operationalPolicy;
     }
 
     /**
@@ -54,9 +74,11 @@ public class LegacyOperationalPolicyProvider {
      *
      * @return the LegacyOperationalPolicy object
      */
-    public LegacyOperationalPolicy createOperationalPolicy(LegacyOperationalPolicy body) {
-        // placeholder
-        return new LegacyOperationalPolicy();
+    public LegacyOperationalPolicy createOperationalPolicy(LegacyOperationalPolicy body) throws PfModelException {
+
+        LegacyOperationalPolicy operationalPolicy = modelsProvider.createOperationalPolicy(body);
+        close();
+        return operationalPolicy;
     }
 
     /**
@@ -65,10 +87,27 @@ public class LegacyOperationalPolicyProvider {
      * @param policyId the ID of policy
      * @param policyVersion the version of policy
      *
-     * @return a string message indicating the operation results
+     * @return the LegacyOperationalPolicy object
+     */
+    public LegacyOperationalPolicy deleteOperationalPolicies(String policyId, String policyVersion)
+            throws PfModelException {
+
+        LegacyOperationalPolicy operationalPolicy = modelsProvider.deleteOperationalPolicy(policyId);
+        close();
+        return operationalPolicy;
+    }
+
+    /**
+     * Closes the connection to database.
+     *
+     * @throws PfModelException the PfModel parsing exception
      */
-    public String deleteOperationalPolicies(String policyId, String policyVersion) {
-        // placeholder
-        return DELETE_OK;
+    private void close() throws PfModelException {
+        try {
+            modelsProvider.close();
+        } catch (Exception e) {
+            throw new PfModelException(
+                    Response.Status.INTERNAL_SERVER_ERROR, "error closing connection to database", e);
+        }
     }
 }
\ No newline at end of file
index 690bdbd..8ce9a49 100644 (file)
 \r
 package org.onap.policy.api.main.rest.provider;\r
 \r
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;\r
+import java.util.List;\r
+import java.util.Map;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.tuple.Pair;\r
+import org.onap.policy.api.main.parameters.ApiParameterGroup;\r
+import org.onap.policy.common.parameters.ParameterService;\r
+import org.onap.policy.models.base.PfModelException;\r
+import org.onap.policy.models.provider.PolicyModelsProvider;\r
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;\r
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
 \r
 /**\r
  * Class to provide all kinds of policy operations.\r
@@ -31,7 +42,18 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
  */\r
 public class PolicyProvider {\r
 \r
-    private static final String DELETE_OK = "Successfully deleted";\r
+    private PolicyModelsProvider modelsProvider;\r
+\r
+    /**\r
+     * Default constructor.\r
+     */\r
+    public PolicyProvider() throws PfModelException {\r
+\r
+        ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");\r
+        PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();\r
+        modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);\r
+        modelsProvider.init();\r
+    }\r
 \r
     /**\r
      * Retrieves a list of policies matching specified ID and version of both policy type and policy.\r
@@ -42,11 +64,61 @@ public class PolicyProvider {
      * @param policyVersion the version of policy\r
      *\r
      * @return the ToscaServiceTemplate object\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
     public ToscaServiceTemplate fetchPolicies(String policyTypeId, String policyTypeVersion,\r
-                                         String policyId, String policyVersion) {\r
-        // placeholder\r
-        return new ToscaServiceTemplate();\r
+            String policyId, String policyVersion) throws PfModelException {\r
+\r
+        validatePathParam(policyTypeId, policyTypeVersion);\r
+        ToscaServiceTemplate serviceTemplate;\r
+        if (policyId == null) {\r
+            serviceTemplate = modelsProvider.getPolicies4PolicyType(policyTypeId, policyTypeVersion);\r
+        } else {\r
+            serviceTemplate = modelsProvider.getPolicies(policyId, policyVersion);\r
+        }\r
+        close();\r
+        return serviceTemplate;\r
+    }\r
+\r
+    /**\r
+     * Retrieves a list of policies with the latest versions that match specified policy type id and version.\r
+     *\r
+     * @param policyTypeId the ID of policy type\r
+     * @param policyTypeVersion the version of policy type\r
+     * @param policyId the ID of the policy\r
+     *\r
+     * @return the ToscaServiceTemplate object\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    public ToscaServiceTemplate fetchLatestPolicies(String policyTypeId, String policyTypeVersion,\r
+            String policyId) throws PfModelException {\r
+\r
+        validatePathParam(policyTypeId, policyTypeVersion);\r
+        ToscaServiceTemplate serviceTemplate = modelsProvider.getLatestPolicies(policyId);\r
+        close();\r
+        return serviceTemplate;\r
+    }\r
+\r
+    /**\r
+     * Retrieves a list of deployed policies in each pdp group.\r
+     *\r
+     * @param policyTypeId the ID of policy type\r
+     * @param policyTypeVersion the version of policy type\r
+     * @param policyId the ID of the policy\r
+     *\r
+     * @return a list of deployed policies in each pdp group\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    public Map<Pair<String, String>, List<ToscaPolicy>> fetchDeployedPolicies(\r
+            String policyTypeId, String policyTypeVersion, String policyId) throws PfModelException {\r
+\r
+        validatePathParam(policyTypeId, policyTypeVersion);\r
+        Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = modelsProvider.getDeployedPolicyList(policyId);\r
+        close();\r
+        return deployedPolicies;\r
     }\r
 \r
     /**\r
@@ -57,26 +129,93 @@ public class PolicyProvider {
      * @param body the entity body of policy\r
      *\r
      * @return the ToscaServiceTemplate object\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
     public ToscaServiceTemplate createPolicy(String policyTypeId, String policyTypeVersion,\r
-                                             ToscaServiceTemplate body) {\r
-        // placeholder\r
-        return new ToscaServiceTemplate();\r
+                                             ToscaServiceTemplate body) throws PfModelException {\r
+\r
+        validatePathParam(policyTypeId, policyTypeVersion);\r
+        validatePolicyTypeMatch(policyTypeId, policyTypeVersion, body);\r
+        ToscaServiceTemplate serviceTemplate = modelsProvider.createPolicies(body);\r
+        close();\r
+        return serviceTemplate;\r
     }\r
 \r
     /**\r
-     * Deletes the policies matching specified ID and version of both policy type and policy.\r
+     * Deletes the policy matching specified ID and version of both policy type and policy.\r
      *\r
      * @param policyTypeId the ID of policy type\r
      * @param policyTypeVersion the version of policy type\r
      * @param policyId the ID of policy\r
      * @param policyVersion the version of policy\r
      *\r
-     * @return a string message indicating the operation results\r
+     * @return the ToscaServiceTemplate object\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    public ToscaServiceTemplate deletePolicy(String policyTypeId, String policyTypeVersion,\r
+                                 String policyId, String policyVersion) throws PfModelException {\r
+\r
+        validatePathParam(policyTypeId, policyTypeVersion);\r
+        ToscaServiceTemplate serviceTemplate = modelsProvider.deletePolicy(policyId, policyVersion);\r
+        close();\r
+        return serviceTemplate;\r
+    }\r
+\r
+    /**\r
+     * Checks the validation of policy type info passed in as path param.\r
+     *\r
+     * @param policyTypeId the ID of policy type\r
+     * @param policyTypeVersion the version of policy type\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    private void validatePathParam(String policyTypeId, String policyTypeVersion) throws PfModelException {\r
+\r
+        // Check policy type existence\r
+        try {\r
+            modelsProvider.getPolicyTypes(policyTypeId, policyTypeVersion);\r
+        } catch (Exception e) {\r
+            throw new PfModelException(Response.Status.NOT_FOUND, "specified policy type does not exist", e);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Validates the match between policy type specified in path param and the one specified in type of policy.\r
+     *\r
+     * @param body the ToscaServiceTemplate to create\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    private void validatePolicyTypeMatch(String policyTypeId, String policyTypeVersion, ToscaServiceTemplate body)\r
+            throws PfModelException {\r
+\r
+        List<Map<String, ToscaPolicy>> policies = body.getToscaTopologyTemplate().getPolicies();\r
+        for (Map<String, ToscaPolicy> policy : policies) {\r
+            if (policy.size() != 1) {\r
+                throw new PfModelException(Response.Status.BAD_REQUEST,\r
+                        "one policy block contains more than one policies");\r
+            }\r
+            ToscaPolicy policyContent = policy.values().iterator().next();\r
+            if (!policyTypeId.equalsIgnoreCase(policyContent.getType())\r
+                    || !policyTypeVersion.equalsIgnoreCase(policyContent.getVersion())) {\r
+                throw new PfModelException(Response.Status.BAD_REQUEST, "policy type info does not match");\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Closes the connection to database.\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    public String deletePolicies(String policyTypeId, String policyTypeVersion,\r
-                                 String policyId, String policyVersion) {\r
-        // placeholder\r
-        return DELETE_OK;\r
+    private void close() throws PfModelException {\r
+        try {\r
+            modelsProvider.close();\r
+        } catch (Exception e) {\r
+            throw new PfModelException(\r
+                    Response.Status.INTERNAL_SERVER_ERROR, "error closing connection to database", e);\r
+        }\r
     }\r
 }
\ No newline at end of file
index 5038e31..04d8a72 100644 (file)
 \r
 package org.onap.policy.api.main.rest.provider;\r
 \r
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;\r
+import javax.ws.rs.core.Response;\r
+import org.onap.policy.api.main.parameters.ApiParameterGroup;\r
+import org.onap.policy.common.parameters.ParameterService;\r
+import org.onap.policy.models.base.PfModelException;\r
+import org.onap.policy.models.provider.PolicyModelsProvider;\r
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;\r
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
 \r
 /**\r
  * Class to provide all kinds of policy type operations.\r
@@ -31,7 +38,18 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
  */\r
 public class PolicyTypeProvider {\r
 \r
-    private static final String DELETE_OK = "Successfully deleted";\r
+    private PolicyModelsProvider modelsProvider;\r
+\r
+    /**\r
+     * Default constructor.\r
+     */\r
+    public PolicyTypeProvider() throws PfModelException {\r
+\r
+        ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");\r
+        PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();\r
+        modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);\r
+        modelsProvider.init();\r
+    }\r
 \r
     /**\r
      * Retrieves a list of policy types matching specified policy type ID and version.\r
@@ -40,10 +58,31 @@ public class PolicyTypeProvider {
      * @param policyTypeVersion the version of policy type\r
      *\r
      * @return the ToscaServiceTemplate object\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    public ToscaServiceTemplate fetchPolicyTypes(String policyTypeId, String policyTypeVersion) {\r
-        // placeholder\r
-        return new ToscaServiceTemplate();\r
+    public ToscaServiceTemplate fetchPolicyTypes(String policyTypeId, String policyTypeVersion)\r
+            throws PfModelException {\r
+\r
+        ToscaServiceTemplate serviceTemplate = modelsProvider.getPolicyTypes(policyTypeId, policyTypeVersion);\r
+        close();\r
+        return serviceTemplate;\r
+    }\r
+\r
+    /**\r
+     * Retrieves a list of policy types with the latest versions.\r
+     *\r
+     * @param policyTypeId the ID of policy type\r
+     *\r
+     * @return the ToscaServiceTemplate object\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    public ToscaServiceTemplate fetchLatestPolicyTypes(String policyTypeId) throws PfModelException {\r
+\r
+        ToscaServiceTemplate serviceTemplate = modelsProvider.getLatestPolicyTypes(policyTypeId);\r
+        close();\r
+        return serviceTemplate;\r
     }\r
 \r
     /**\r
@@ -51,23 +90,45 @@ public class PolicyTypeProvider {
      *\r
      * @param body the entity body of policy type\r
      *\r
-     * @return the ToscaServiceTemplate objects\r
+     * @return the ToscaServiceTemplate object\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    public ToscaServiceTemplate createPolicyType(ToscaServiceTemplate body) {\r
-        // placeholder\r
-        return new ToscaServiceTemplate();\r
+    public ToscaServiceTemplate createPolicyType(ToscaServiceTemplate body) throws PfModelException {\r
+\r
+        ToscaServiceTemplate serviceTemplate = modelsProvider.createPolicyTypes(body);\r
+        close();\r
+        return serviceTemplate;\r
     }\r
 \r
     /**\r
-     * Delete the policy types matching specified policy type ID and version.\r
+     * Delete the policy type matching specified policy type ID and version.\r
      *\r
      * @param policyTypeId the ID of policy type\r
      * @param policyTypeVersion the version of policy type\r
      *\r
-     * @return a string message indicating the operation results\r
+     * @return the ToscaServiceTemplate object\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    public ToscaServiceTemplate deletePolicyType(String policyTypeId, String policyTypeVersion)\r
+            throws PfModelException {\r
+\r
+        ToscaServiceTemplate serviceTemplate = modelsProvider.deletePolicyType(policyTypeId, policyTypeVersion);\r
+        close();\r
+        return serviceTemplate;\r
+    }\r
+\r
+    /**\r
+     * Closes the connection to database.\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    public String deletePolicyTypes(String policyTypeId, String policyTypeVersion) {\r
-        // placeholder\r
-        return DELETE_OK;\r
+    private void close() throws PfModelException {\r
+        try {\r
+            modelsProvider.close();\r
+        } catch (Exception e) {\r
+            throw new PfModelException(\r
+                    Response.Status.INTERNAL_SERVER_ERROR, "error closing connection to database", e);\r
+        }\r
     }\r
 }\r
diff --git a/main/src/main/resources/META-INF/persistence.xml b/main/src/main/resources/META-INF/persistence.xml
new file mode 100644 (file)
index 0000000..81be3db
--- /dev/null
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ============LICENSE_START=======================================================
+   Copyright (C) 2019 Nordix Foundation.
+  ================================================================================
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+  
+       http://www.apache.org/licenses/LICENSE-2.0
+  
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  
+  SPDX-License-Identifier: Apache-2.0
+  ============LICENSE_END=========================================================
+-->
+
+<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
+    <persistence-unit name="ToscaConceptTest" transaction-type="RESOURCE_LOCAL">
+        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+
+        <class>org.onap.policy.models.dao.converters.CDataConditioner</class>
+        <class>org.onap.policy.models.dao.converters.Uuid2String</class>
+        <class>org.onap.policy.models.base.PfConceptKey</class>
+        <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType</class>
+        <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy</class>
+
+        <properties>
+            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
+            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb" />
+            <property name="javax.persistence.jdbc.user" value="policy" />
+            <property name="javax.persistence.jdbc.password" value="P01icY" />
+            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
+            <property name="eclipselink.ddl-generation.output-mode" value="database" />
+            <property name="eclipselink.logging.level" value="INFO" />
+        </properties>
+    </persistence-unit>
+
+    <persistence-unit name="ToscaConceptMariaDBTest" transaction-type="RESOURCE_LOCAL">
+        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+
+        <class>org.onap.policy.models.dao.converters.CDataConditioner</class>
+        <class>org.onap.policy.models.dao.converters.Uuid2String</class>
+        <class>org.onap.policy.models.base.PfConceptKey</class>
+        <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType</class>
+        <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy</class>
+
+        <properties>
+            <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" />
+            <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:3306/policy" />
+            <property name="javax.persistence.jdbc.user" value="policy" />
+            <property name="javax.persistence.jdbc.password" value="P01icY" />
+            <property name="javax.persistence.schema-generation.database.action" value="create" />
+
+            <!-- property name="eclipselink.logging.level" value="ALL" />
+            <property name="eclipselink.logging.level.jpa" value="ALL" />
+            <property name="eclipselink.logging.level.ddl" value="ALL" />
+            <property name="eclipselink.logging.level.connection" value="ALL" />
+            <property name="eclipselink.logging.level.sql" value="ALL" />
+            <property name="eclipselink.logging.level.transaction" value="ALL" />
+            <property name="eclipselink.logging.level.sequencing" value="ALL" />
+            <property name="eclipselink.logging.level.server" value="ALL" />
+            <property name="eclipselink.logging.level.query" value="ALL" />
+            <property name="eclipselink.logging.level.properties" value="ALL" /-->
+
+            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
+            <property name="eclipselink.ddl-generation.output-mode" value="database" />
+            <property name="eclipselink.logging.level" value="INFO" />
+        </properties>
+    </persistence-unit>
+</persistence>
index 8ff2f98..f0f971d 100644 (file)
@@ -1,7 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
- * ONAP Policy API 
- * ================================================================================ 
+ * ONAP Policy API
+ * ================================================================================
  * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
 
 package org.onap.policy.api.main.parameters;
 
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
+
 /**
  * Class to hold/create all parameters for test cases.
  *
  */
 public class CommonTestData {
 
+    public static final String API_GROUP_NAME = "ApiGroup";
+
     private static final String REST_SERVER_PASSWORD = "zb!XztG34";
     private static final String REST_SERVER_USER = "healthcheck";
     private static final int REST_SERVER_PORT = 6969;
     private static final String REST_SERVER_HOST = "0.0.0.0";
     private static final boolean REST_SERVER_HTTPS = false;
     private static final boolean REST_SERVER_AAF = false;
-    public static final String API_GROUP_NAME = "ApiGroup";
+
+    private static final String PROVIDER_GROUP_NAME = "PolicyProviderParameterGroup";
+    private static final String PROVIDER_IMPL = "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl";
+    private static final String DATABASE_URL = "jdbc:h2:mem:testdb";
+    private static final String DATABASE_USER = "policy";
+    private static final String DATABASE_PASSWORD = "P01icY";
+    private static final String PERSISTENCE_UNIT = "ToscaConceptTest";
 
     /**
      * Returns an instance of RestServerParameters for test cases.
@@ -54,4 +64,25 @@ public class CommonTestData {
         return restServerParameters;
     }
 
+    /**
+     * Returns an instance of PolicyModelsProviderParameters for test cases.
+     *
+     * @param isEmpty boolean value to represent that object created should be empty or not
+     * @return the PolicyModelsProviderParameters object
+     */
+    public PolicyModelsProviderParameters getDatabaseProviderParameters(final boolean isEmpty) {
+        final PolicyModelsProviderParameters databaseProviderParameters;
+        if (!isEmpty) {
+            databaseProviderParameters = new PolicyModelsProviderParameters();
+            databaseProviderParameters.setName(PROVIDER_GROUP_NAME);
+            databaseProviderParameters.setImplementation(PROVIDER_IMPL);
+            databaseProviderParameters.setDatabaseUrl(DATABASE_URL);
+            databaseProviderParameters.setDatabaseUser(DATABASE_USER);
+            databaseProviderParameters.setDatabasePassword(DATABASE_PASSWORD);
+            databaseProviderParameters.setPersistenceUnit(PERSISTENCE_UNIT);
+        } else {
+            databaseProviderParameters = new PolicyModelsProviderParameters();
+        }
+        return databaseProviderParameters;
+    }
 }
index 184f242..8be5245 100644 (file)
@@ -1,16 +1,15 @@
 /*-
  * ============LICENSE_START=======================================================
- * ONAP Policy API 
- * ================================================================================ 
+ * ONAP Policy API
+ * ================================================================================
  * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 IBM.
  * ================================================================================
  * 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 
+ *      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,
@@ -30,6 +29,7 @@ import static org.junit.Assert.assertTrue;
 
 import org.junit.Test;
 import org.onap.policy.common.parameters.GroupValidationResult;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 
 /**
  * Class to perform unit test of ApiParameterGroup.
@@ -41,14 +41,18 @@ public class TestApiParameterGroup {
     @Test
     public void testApiParameterGroup() {
         final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false);
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME,
-                restServerParameters);
+        final PolicyModelsProviderParameters databaseProviderParameters =
+                commonTestData.getDatabaseProviderParameters(false);
+        final ApiParameterGroup apiParameters = new ApiParameterGroup(
+                CommonTestData.API_GROUP_NAME, restServerParameters, databaseProviderParameters);
         final GroupValidationResult validationResult = apiParameters.validate();
         assertTrue(validationResult.isValid());
         assertEquals(restServerParameters.getHost(), apiParameters.getRestServerParameters().getHost());
         assertEquals(restServerParameters.getPort(), apiParameters.getRestServerParameters().getPort());
-        assertEquals(restServerParameters.getUserName(), apiParameters.getRestServerParameters().getUserName());
-        assertEquals(restServerParameters.getPassword(), apiParameters.getRestServerParameters().getPassword());
+        assertEquals(restServerParameters.getUserName(),
+                apiParameters.getRestServerParameters().getUserName());
+        assertEquals(restServerParameters.getPassword(),
+                apiParameters.getRestServerParameters().getPassword());
         assertEquals(restServerParameters.isHttps(), apiParameters.getRestServerParameters().isHttps());
         assertEquals(restServerParameters.isAaf(), apiParameters.getRestServerParameters().isAaf());
         assertEquals(CommonTestData.API_GROUP_NAME, apiParameters.getName());
@@ -57,52 +61,57 @@ public class TestApiParameterGroup {
     @Test
     public void testApiParameterGroup_NullName() {
         final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false);
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(null, restServerParameters);
+        final PolicyModelsProviderParameters databaseProviderParameters =
+                commonTestData.getDatabaseProviderParameters(false);
+        final ApiParameterGroup apiParameters = new ApiParameterGroup(null,
+                        restServerParameters, databaseProviderParameters);
         final GroupValidationResult validationResult = apiParameters.validate();
         assertFalse(validationResult.isValid());
         assertEquals(null, apiParameters.getName());
-        assertTrue(validationResult.getResult().contains(
-                "field \"name\" type \"java.lang.String\" value \"null\" INVALID, " + "must be a non-blank string"));
+        assertTrue(validationResult.getResult()
+                        .contains("field \"name\" type \"java.lang.String\" value \"null\" INVALID, "
+                                        + "must be a non-blank string"));
     }
 
     @Test
     public void testApiParameterGroup_EmptyName() {
         final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false);
-
-        final ApiParameterGroup apiParameters = new ApiParameterGroup("", restServerParameters);
+        final PolicyModelsProviderParameters databaseProviderParameters =
+                commonTestData.getDatabaseProviderParameters(false);
+        final ApiParameterGroup apiParameters = new ApiParameterGroup("",
+                        restServerParameters, databaseProviderParameters);
         final GroupValidationResult validationResult = apiParameters.validate();
         assertFalse(validationResult.isValid());
         assertEquals("", apiParameters.getName());
-        assertTrue(validationResult.getResult().contains(
-                "field \"name\" type \"java.lang.String\" value \"\" INVALID, " + "must be a non-blank string"));
+        assertTrue(validationResult.getResult().contains("field \"name\" type \"java.lang.String\" value \"\" INVALID, "
+                        + "must be a non-blank string"));
     }
 
     @Test
     public void testApiParameterGroup_EmptyRestServerParameters() {
         final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(true);
-
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME,
-                restServerParameters);
+        final PolicyModelsProviderParameters databaseProviderParameters =
+                commonTestData.getDatabaseProviderParameters(false);
+        final ApiParameterGroup apiParameters = new ApiParameterGroup(
+                        CommonTestData.API_GROUP_NAME, restServerParameters, databaseProviderParameters);
         final GroupValidationResult validationResult = apiParameters.validate();
         assertFalse(validationResult.isValid());
         assertTrue(validationResult.getResult()
-                .contains("\"org.onap.policy.api.main.parameters.RestServerParameters\" INVALID, "
-                        + "parameter group has status INVALID"));
+                        .contains("\"org.onap.policy.api.main.parameters.RestServerParameters\" INVALID, "
+                                        + "parameter group has status INVALID"));
     }
 
     @Test
-    public void testName() {
+    public void testApiParameterGroup_EmptyDatabaseProviderParameters() {
         final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false);
-
-        final ApiParameterGroup apiParameters = new ApiParameterGroup("", restServerParameters);
-        apiParameters.setName("name");
-        assertEquals("name", apiParameters.getName());
-    }
-
-    @Test
-    public void testVaildateForNullRestServiceParameters() {
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME, null);
+        final PolicyModelsProviderParameters databaseProviderParameters =
+                commonTestData.getDatabaseProviderParameters(true);
+        final ApiParameterGroup apiParameters = new ApiParameterGroup(
+                        CommonTestData.API_GROUP_NAME, restServerParameters, databaseProviderParameters);
         final GroupValidationResult validationResult = apiParameters.validate();
-        assertTrue(validationResult.getResult().contains("parameter group has status INVALID"));
+        assertFalse(validationResult.isValid());
+        assertTrue(validationResult.getResult()
+                        .contains("\"org.onap.policy.models.provider.PolicyModelsProviderParameters\" INVALID, "
+                                        + "parameter group has status INVALID"));
     }
 }
index 71d8c35..480a5d8 100644 (file)
@@ -28,7 +28,6 @@ import static org.junit.Assert.fail;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
-
 import org.junit.Test;
 import org.onap.policy.api.main.exception.PolicyApiException;
 import org.onap.policy.api.main.startstop.ApiCommandLineArguments;
@@ -153,7 +152,7 @@ public class TestApiParameterHandler {
     @Test
     public void testApiParameterGroup_InvalidRestServerParameters()
             throws PolicyApiException, IOException {
-        final String[] apiConfigParameters = 
+        final String[] apiConfigParameters =
             { "-c", "parameters/ApiConfigParameters_InvalidRestServerParameters.json" };
         final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
         arguments.parse(apiConfigParameters);
index 3c8b251..4fb588c 100644 (file)
@@ -140,11 +140,11 @@ public class TestApiRestServer {
             main = startApiService(true);
             Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
             StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
-            validateStatisticsReport(report, 0, 200);
+            validateStatisticsReport(report, 200);
             updateApiStatistics();
             invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
             report = invocationBuilder.get(StatisticsReport.class);
-            validateStatisticsReport(report, 1, 200);
+            validateStatisticsReport(report, 200);
             ApiStatisticsManager.resetAllStatistics();
         } catch (final Exception exp) {
             LOGGER.error("testApiStatistics_200 failed", exp);
@@ -161,7 +161,7 @@ public class TestApiRestServer {
             restServer.start();
             final Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
             final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
-            validateStatisticsReport(report, 0, 500);
+            validateStatisticsReport(report, 500);
             ApiStatisticsManager.resetAllStatistics();
         } catch (final Exception exp) {
             LOGGER.error("testApiStatistics_500 failed", exp);
@@ -175,7 +175,7 @@ public class TestApiRestServer {
             main = startApiService(false);
             final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
             final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
-            validateStatisticsReport(report, 0, 200);
+            validateStatisticsReport(report, 200);
         } catch (final Exception exp) {
             LOGGER.error("testHttpsApiStatistics failed", exp);
             fail("Test should not throw an exception");
@@ -283,23 +283,8 @@ public class TestApiRestServer {
         ApiStatisticsManager.updatePolicyTypePostFailureCount();
     }
 
-    private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) {
+    private void validateStatisticsReport(final StatisticsReport report, final int code) {
         assertEquals(code, report.getCode());
-        assertEquals(count, report.getTotalApiCallCount());
-        assertEquals(count, report.getApiCallSuccessCount());
-        assertEquals(count, report.getApiCallFailureCount());
-        assertEquals(count, report.getTotalPolicyGetCount());
-        assertEquals(count, report.getTotalPolicyPostCount());
-        assertEquals(count, report.getTotalPolicyTypeGetCount());
-        assertEquals(count, report.getTotalPolicyTypePostCount());
-        assertEquals(count, report.getPolicyGetSuccessCount());
-        assertEquals(count, report.getPolicyGetFailureCount());
-        assertEquals(count, report.getPolicyPostSuccessCount());
-        assertEquals(count, report.getPolicyPostFailureCount());
-        assertEquals(count, report.getPolicyTypeGetSuccessCount());
-        assertEquals(count, report.getPolicyTypeGetFailureCount());
-        assertEquals(count, report.getPolicyTypePostSuccessCount());
-        assertEquals(count, report.getPolicyTypePostFailureCount());
     }
 
     private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code,
@@ -1,6 +1,8 @@
 /*-
  * ============LICENSE_START=======================================================
- *  Copyright (C) 2019 IBM.
+ * ONAP Policy API
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. 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.
  * ============LICENSE_END=========================================================
  */
 
-package org.onap.policy.api.main.exception;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Before;
-import org.junit.Test;
 
-public class PolicyApiRuntimeExceptionTest {
+package org.onap.policy.api.main.rest.provider;
 
-    private PolicyApiRuntimeException policyApiRuntimeException;
-    private String message = "test exception message";
-    
-    @Before
-    public void setUp() {
-        policyApiRuntimeException = new PolicyApiRuntimeException(message);
-    }
-    
-    @Test
-    public void testContructor() {
-        policyApiRuntimeException = new PolicyApiRuntimeException(message, new Exception());
-        assertEquals(message, policyApiRuntimeException.getMessage());
-    }
-}
+public class TestLegacyGuardPolicyProvider {}
diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java
new file mode 100644 (file)
index 0000000..de12fca
--- /dev/null
@@ -0,0 +1,26 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy API
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+
+package org.onap.policy.api.main.rest.provider;
+
+public class TestLegacyOperationalPolicyProvider {}
diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java
new file mode 100644 (file)
index 0000000..11d7e40
--- /dev/null
@@ -0,0 +1,25 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy API
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.rest.provider;
+
+public class TestPolicyProvider {}
diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java
new file mode 100644 (file)
index 0000000..d60dc2e
--- /dev/null
@@ -0,0 +1,25 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy API
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.rest.provider;
+
+public class TestPolicyTypeProvider {}
diff --git a/main/src/test/resources/META-INF/persistence.xml b/main/src/test/resources/META-INF/persistence.xml
new file mode 100644 (file)
index 0000000..23e8567
--- /dev/null
@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ============LICENSE_START=======================================================
+   Copyright (C) 2019 Nordix Foundation.
+  ================================================================================
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+  
+       http://www.apache.org/licenses/LICENSE-2.0
+  
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  
+  SPDX-License-Identifier: Apache-2.0
+  ============LICENSE_END=========================================================
+-->
+
+<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
+    <persistence-unit name="ToscaConceptTest" transaction-type="RESOURCE_LOCAL">
+        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+
+        <class>org.onap.policy.models.dao.converters.CDataConditioner</class>
+        <class>org.onap.policy.models.dao.converters.Uuid2String</class>
+        <class>org.onap.policy.models.base.PfConceptKey</class>
+        <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType</class>
+        <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy</class>
+
+        <properties>
+            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
+            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb" />
+            <property name="javax.persistence.jdbc.user" value="policy" />
+            <property name="javax.persistence.jdbc.password" value="P01icY" />
+            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
+            <property name="eclipselink.ddl-generation.output-mode" value="database" />
+            <property name="eclipselink.logging.level" value="INFO" />
+        </properties>
+    </persistence-unit>
+
+    <persistence-unit name="ToscaConceptMariaDBTest" transaction-type="RESOURCE_LOCAL">
+        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+
+        <class>org.onap.policy.models.dao.converters.CDataConditioner</class>
+        <class>org.onap.policy.models.dao.converters.Uuid2String</class>
+        <class>org.onap.policy.models.base.PfConceptKey</class>
+        <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy</class>
+
+        <properties>
+            <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" />
+            <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:3306/policy" />
+            <property name="javax.persistence.jdbc.user" value="policy" />
+            <property name="javax.persistence.jdbc.password" value="P01icY" />
+            <property name="javax.persistence.schema-generation.database.action" value="create" />
+
+            <!-- property name="eclipselink.logging.level" value="ALL" />
+            <property name="eclipselink.logging.level.jpa" value="ALL" />
+            <property name="eclipselink.logging.level.ddl" value="ALL" />
+            <property name="eclipselink.logging.level.connection" value="ALL" />
+            <property name="eclipselink.logging.level.sql" value="ALL" />
+            <property name="eclipselink.logging.level.transaction" value="ALL" />
+            <property name="eclipselink.logging.level.sequencing" value="ALL" />
+            <property name="eclipselink.logging.level.server" value="ALL" />
+            <property name="eclipselink.logging.level.query" value="ALL" />
+            <property name="eclipselink.logging.level.properties" value="ALL" /-->
+
+            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
+            <property name="eclipselink.ddl-generation.output-mode" value="database" />
+            <property name="eclipselink.logging.level" value="INFO" />
+        </properties>
+    </persistence-unit>
+</persistence>
index 8fae123..c64271c 100644 (file)
@@ -5,5 +5,13 @@
         "port":6969,
         "userName":"healthcheck",
         "password":"zb!XztG34"
+    },
+    "databaseProviderParameters": {
+        "name": "PolicyProviderParameterGroup",
+        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+        "databaseUrl": "jdbc:mariadb://localhost:3306/policy",
+        "databaseUser": "policy",
+        "databasePassword": "UDAxaWNZ",
+        "persistenceUnit": "ToscaConceptMariaDBTest"
     }
 }
index ec73213..878dc1f 100644 (file)
@@ -6,5 +6,13 @@
         "userName":"healthcheck",
         "password":"zb!XztG34",
         "https":true
+    },
+    "databaseProviderParameters": {
+        "name": "PolicyProviderParameterGroup",
+        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+        "databaseUrl": "jdbc:h2:mem:testdb",
+        "databaseUser": "policy",
+        "databasePassword": "UDAxaWNZ",
+        "persistenceUnit": "ToscaConceptTest"
     }
 }
index 2d394fb..67e461e 100644 (file)
@@ -5,5 +5,13 @@
         "port":-1,
         "userName":"",
         "password":""
+    },
+    "databaseProviderParameters": {
+        "name": "PolicyProviderParameterGroup",
+        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+        "databaseUrl": "jdbc:h2:mem:testdb",
+        "databaseUser": "policy",
+        "databasePassword": "UDAxaWNZ",
+        "persistenceUnit": "ToscaConceptTest"
     }
 }
index 61c6c86..2600d20 100644 (file)
@@ -5,5 +5,13 @@
         "port":6969,
         "userName":"healthcheck",
         "password":"zb!XztG34"
+    },
+    "databaseProviderParameters": {
+        "name": "PolicyProviderParameterGroup",
+        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+        "databaseUrl": "jdbc:h2:mem:testdb",
+        "databaseUser": "policy",
+        "databasePassword": "UDAxaWNZ",
+        "persistenceUnit": "ToscaConceptTest"
     }
 }
index 6b0805d..ed2fbde 100644 (file)
@@ -4,5 +4,13 @@
         "port":6969,
         "userName":"healthcheck",
         "password":"zb!XztG34"
+    },
+    "databaseProviderParameters": {
+        "name": "PolicyProviderParameterGroup",
+        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+        "databaseUrl": "jdbc:h2:mem:testdb",
+        "databaseUser": "policy",
+        "databasePassword": "UDAxaWNZ",
+        "persistenceUnit": "ToscaConceptTest"
     }
 }
\ No newline at end of file
diff --git a/main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.json b/main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.json
new file mode 100644 (file)
index 0000000..26f4c02
--- /dev/null
@@ -0,0 +1,28 @@
+{
+  "tosca_definitions_version": "tosca_simple_yaml_1_0_0",
+  "policy_types": [
+    {
+      "onap.policies.Monitoring": {
+        "derived_from": "tosca.policies.Root",
+        "description": "a base policy type for all policies that govern monitoring provision",
+        "version": "1.0.0"
+      }
+    },
+    {
+      "onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server": {
+        "derived_from": "policy.nodes.Root",
+        "version": "1.0.0",
+        "properties": {
+          "buscontroller_feed_publishing_endpoint": {
+            "type": "string",
+            "description": "DMAAP Bus Controller feed endpoint"
+          },
+          "datafile.policy": {
+            "type": "string",
+            "description": "datafile Policy JSON as string"
+          }
+        }
+      }
+    }
+  ]
+}
\ No newline at end of file
index 5a093dd..63796fa 100644 (file)
@@ -1,17 +1,18 @@
 tosca_definitions_version: tosca_simple_yaml_1_0_0
 policy_types:
-  version: 1.0.0
-  onap.policies.Monitoring:
-    derived_from: tosca.policies.Root
-    description: a base policy type for all policies that govern monitoring provision
-    version: 1.0.0
-  onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server:
-    derived_from: policy.nodes.Root
-    version: 1.0.0
-    properties:
-      buscontroller_feed_publishing_endpoint:
-        type: string
-        description: DMAAP Bus Controller feed endpoint
-      datafile.policy:
-        type: string
-        description: datafile Policy JSON as string
+  -
+    onap.policies.Monitoring:
+        derived_from: tosca.policies.Root
+        description: a base policy type for all policies that govern monitoring provision
+        version: 1.0.0
+  -
+    onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server:
+        derived_from: policy.nodes.Root
+        version: 1.0.0
+        properties:
+            buscontroller_feed_publishing_endpoint:
+                type: string
+                description: DMAAP Bus Controller feed endpoint
+            datafile.policy:
+                type: string
+                description: datafile Policy JSON as string
\ No newline at end of file
diff --git a/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json b/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json
new file mode 100644 (file)
index 0000000..95d7a53
--- /dev/null
@@ -0,0 +1,223 @@
+{
+  "tosca_definitions_version": "tosca_simple_yaml_1_0_0",
+  "policy_types": [
+    {
+      "onap.policies.Monitoring": {
+        "derived_from": "tosca.policies.Root",
+        "description": "a base policy type for all policies that governs monitoring provisioning"
+      }
+    },
+    {
+      "onap.policy.monitoring.cdap.tca.hi.lo.app": {
+        "derived_from": "onap.policies.Monitoring",
+        "version": "1.0.0",
+        "properties": {
+          "tca_policy": {
+            "type": "map",
+            "description": "TCA Policy JSON",
+            "entry_schema": {
+              "type": "onap.datatypes.monitoring.tca_policy"
+            }
+          }
+        }
+      }
+    }
+  ],
+  "data_types": [
+    {
+      "onap.datatypes.monitoring.metricsPerEventName": {
+        "derived_from": "tosca.datatypes.Root",
+        "properties": {
+          "controlLoopSchemaType": {
+            "type": "string",
+            "required": true,
+            "description": "Specifies Control Loop Schema Type for the event Name e.g. VNF, VM",
+            "constraints": [
+              {
+                "valid_values": [
+                  "VM",
+                  "VNF"
+                ]
+              }
+            ]
+          },
+          "eventName": {
+            "type": "string",
+            "required": true,
+            "description": "Event name to which thresholds need to be applied"
+          },
+          "policyName": {
+            "type": "string",
+            "required": true,
+            "description": "TCA Policy Scope Name"
+          },
+          "policyScope": {
+            "type": "string",
+            "required": true,
+            "description": "TCA Policy Scope"
+          },
+          "policyVersion": {
+            "type": "string",
+            "required": true,
+            "description": "TCA Policy Scope Version"
+          },
+          "thresholds": {
+            "type": "list",
+            "required": true,
+            "description": "Thresholds associated with eventName",
+            "entry_schema": {
+              "type": "onap.datatypes.monitoring.thresholds"
+            }
+          }
+        }
+      }
+    },
+    {
+      "onap.datatypes.monitoring.tca_policy": {
+        "derived_from": "tosca.datatypes.Root",
+        "properties": {
+          "domain": {
+            "type": "string",
+            "required": true,
+            "description": "Domain name to which TCA needs to be applied",
+            "default": "measurementsForVfScaling",
+            "constraints": [
+              {
+                "equal": "measurementsForVfScaling"
+              }
+            ]
+          },
+          "metricsPerEventName": {
+            "type": "list",
+            "required": true,
+            "description": "Contains eventName and threshold details that need to be applied to given eventName",
+            "entry_schema": {
+              "type": "onap.datatypes.monitoring.metricsPerEventName"
+            }
+          }
+        }
+      }
+    },
+    {
+      "onap.datatypes.monitoring.thresholds": {
+        "derived_from": "tosca.datatypes.Root",
+        "properties": {
+          "closedLoopControlName": {
+            "type": "string",
+            "required": true,
+            "description": "Closed Loop Control Name associated with the threshold"
+          },
+          "closedLoopEventStatus": {
+            "type": "string",
+            "required": true,
+            "description": "Closed Loop Event Status of the threshold",
+            "constraints": [
+              {
+                "valid_values": [
+                  "ONSET",
+                  "ABATED"
+                ]
+              }
+            ]
+          },
+          "direction": {
+            "type": "string",
+            "required": true,
+            "description": "Direction of the threshold",
+            "constraints": [
+              {
+                "valid_values": [
+                  "LESS",
+                  "LESS_OR_EQUAL",
+                  "GREATER",
+                  "GREATER_OR_EQUAL",
+                  "EQUAL"
+                ]
+              }
+            ]
+          },
+          "fieldPath": {
+            "type": "string",
+            "required": true,
+            "description": "Json field Path as per CEF message which needs to be analyzed for TCA",
+            "constraints": [
+              {
+                "valid_values": [
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsDelta",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsAccumulated",
+                  "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuIdle",
+                  "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageInterrupt",
+                  "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageNice",
+                  "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSoftIrq",
+                  "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSteal",
+                  "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSystem",
+                  "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuWait",
+                  "$.event.measurementsForVfScalingFields.cpuUsageArray[*].percentUsage",
+                  "$.event.measurementsForVfScalingFields.meanRequestLatency",
+                  "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryBuffered",
+                  "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryCached",
+                  "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryConfigured",
+                  "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryFree",
+                  "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryUsed",
+                  "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value"
+                ]
+              }
+            ]
+          },
+          "severity": {
+            "type": "string",
+            "required": true,
+            "description": "Threshold Event Severity",
+            "constraints": [
+              {
+                "valid_values": [
+                  "CRITICAL",
+                  "MAJOR",
+                  "MINOR",
+                  "WARNING",
+                  "NORMAL"
+                ]
+              }
+            ]
+          },
+          "thresholdValue": {
+            "type": "integer",
+            "required": true,
+            "description": "Threshold value for the field Path inside CEF message"
+          },
+          "version": {
+            "type": "string",
+            "required": true,
+            "description": "Version number associated with the threshold"
+          }
+        }
+      }
+    }
+  ]
+}
\ No newline at end of file
index 699cffd..f8e9b75 100644 (file)
@@ -1,8 +1,10 @@
 tosca_definitions_version: tosca_simple_yaml_1_0_0
 policy_types:
+  -
     onap.policies.Monitoring:
         derived_from: tosca.policies.Root
         description: a base policy type for all policies that governs monitoring provisioning
+  -
     onap.policy.monitoring.cdap.tca.hi.lo.app:
         derived_from: onap.policies.Monitoring
         version: 1.0.0
@@ -13,6 +15,7 @@ policy_types:
                 entry_schema:
                     type: onap.datatypes.monitoring.tca_policy
 data_types:
+  -
     onap.datatypes.monitoring.metricsPerEventName:
         derived_from: tosca.datatypes.Root
         properties:
@@ -46,6 +49,7 @@ data_types:
                 description: Thresholds associated with eventName
                 entry_schema:
                     type: onap.datatypes.monitoring.thresholds
+  -
     onap.datatypes.monitoring.tca_policy:
         derived_from: tosca.datatypes.Root
         properties:
@@ -62,6 +66,7 @@ data_types:
                 description: Contains eventName and threshold details that need to be applied to given eventName
                 entry_schema:
                     type: onap.datatypes.monitoring.metricsPerEventName
+  -
     onap.datatypes.monitoring.thresholds:
         derived_from: tosca.datatypes.Root
         properties:
@@ -155,4 +160,4 @@ data_types:
             version:
                 type: string
                 required: true
-                description: Version number associated with the threshold
+                description: Version number associated with the threshold
\ No newline at end of file
index f7aaf39..260fac5 100644 (file)
@@ -7,5 +7,13 @@
         "password": "zb!XztG34",
         "https": true,
         "aaf": false 
+    },
+    "databaseProviderParameters": {
+        "name": "PolicyProviderParameterGroup",
+        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+        "databaseUrl": "jdbc:mariadb://localhost:3306/policy",
+        "databaseUser": "policy",
+        "databasePassword": "UDAxaWNZ",
+        "persistenceUnit": "ToscaConceptMariaDBTest"
     }
 }
index 6df43f7..e0ed3fb 100644 (file)
@@ -7,5 +7,13 @@
         "password": "zb!XztG34",
         "https": true,
         "aaf": false 
+    },
+    "databaseProviderParameters": {
+        "name": "PolicyProviderParameterGroup",
+        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+        "databaseUrl": "jdbc:mariadb://localhost:3306/policy",
+        "databaseUser": "policy",
+        "databasePassword": "UDAxaWNZ",
+        "persistenceUnit": "ToscaConceptMariaDBTest"
     }
 }
\ No newline at end of file