summaryrefslogtreecommitdiffstats
path: root/main
diff options
context:
space:
mode:
authorChenfei Gao <cgao@research.att.com>2019-04-02 08:55:17 -0400
committerChenfei Gao <cgao@research.att.com>2019-04-03 16:56:17 -0400
commite156fb8bf79ee361793af0aef4db5228c4c16f20 (patch)
treef2cb030cf8811a1912d311baac3e7cc3dd874699 /main
parenta53aca032be0550f856c7eb8de5c8d492b7dd0ca (diff)
Implement policy provider functions
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>
Diffstat (limited to 'main')
-rw-r--r--main/pom.xml9
-rw-r--r--main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java22
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java411
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/ApiRestServer.java4
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java284
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java70
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java65
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java167
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java89
-rw-r--r--main/src/main/resources/META-INF/persistence.xml75
-rw-r--r--main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java37
-rw-r--r--main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java71
-rw-r--r--main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java3
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java25
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java (renamed from main/src/test/java/org/onap/policy/api/main/exception/PolicyApiRuntimeExceptionTest.java)27
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java26
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java25
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java25
-rw-r--r--main/src/test/resources/META-INF/persistence.xml74
-rw-r--r--main/src/test/resources/parameters/ApiConfigParameters.json8
-rw-r--r--main/src/test/resources/parameters/ApiConfigParameters_Https.json8
-rw-r--r--main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json8
-rw-r--r--main/src/test/resources/parameters/MinimumParameters.json8
-rw-r--r--main/src/test/resources/parameters/NoParameters.json8
-rw-r--r--main/src/test/resources/policies/vDNS.policy.guard.minmax.input.json1
-rw-r--r--main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.json28
-rw-r--r--main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml31
-rw-r--r--main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json223
-rw-r--r--main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml7
29 files changed, 1404 insertions, 435 deletions
diff --git a/main/pom.xml b/main/pom.xml
index db306112..381d39f1 100644
--- a/main/pom.xml
+++ b/main/pom.xml
@@ -68,6 +68,15 @@
<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>
diff --git a/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java b/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java
index af12f016..9727b239 100644
--- a/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java
+++ b/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java
@@ -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;
}
/**
@@ -73,6 +78,15 @@ public class ApiParameterGroup implements ParameterGroup {
}
/**
+ * Return the databaseProviderParameters of this parameter group instance.
+ *
+ * @return the databaseProviderParameters
+ */
+ public PolicyModelsProviderParameters getDatabaseProviderParameters() {
+ return databaseProviderParameters;
+ }
+
+ /**
* Validate the parameter group.
*
* @return the result of the validation
@@ -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;
}
}
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
index 0f68882f..500c5a89 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
@@ -36,6 +36,8 @@ import io.swagger.annotations.Info;
import io.swagger.annotations.ResponseHeader;
import io.swagger.annotations.SecurityDefinition;
import io.swagger.annotations.SwaggerDefinition;
+import java.util.List;
+import java.util.Map;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@@ -45,15 +47,18 @@ import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
+import org.apache.commons.lang3.tuple.Pair;
import org.onap.policy.api.main.rest.provider.HealthCheckProvider;
import org.onap.policy.api.main.rest.provider.PolicyProvider;
import org.onap.policy.api.main.rest.provider.PolicyTypeProvider;
import org.onap.policy.api.main.rest.provider.StatisticsProvider;
import org.onap.policy.common.endpoints.report.HealthCheckReport;
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.base.PfModelRuntimeException;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
/**
* Class to provide REST API services.
@@ -126,6 +131,8 @@ public class ApiRestController {
})
public Response getHealthCheck(
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
+
+ updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(new HealthCheckProvider().performHealthCheck()).build();
}
@@ -172,6 +179,8 @@ public class ApiRestController {
})
public Response getStatistics(
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
+
+ updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(new StatisticsProvider().fetchCurrentStatistics()).build();
}
@@ -218,8 +227,18 @@ public class ApiRestController {
})
public Response getAllPolicyTypes(
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyTypeProvider().fetchPolicyTypes(null, null)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider().fetchPolicyTypes(null, null);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
@@ -268,8 +287,19 @@ public class ApiRestController {
public Response getAllVersionsOfPolicyType(
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyTypeProvider().fetchPolicyTypes(policyTypeId, null)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()
+ .fetchPolicyTypes(policyTypeId, null);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
@@ -320,8 +350,19 @@ public class ApiRestController {
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
@PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyTypeProvider().fetchPolicyTypes(policyTypeId, versionId)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()
+ .fetchPolicyTypes(policyTypeId, versionId);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
@@ -370,33 +411,37 @@ public class ApiRestController {
public Response createPolicyType(
@ApiParam(value = "Entity body of policy type", required = true) ToscaServiceTemplate body,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyTypeProvider().createPolicyType(body)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider().createPolicyType(body);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.POST);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.POST);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
- * Deletes all versions of a particular policy type.
+ * Deletes specified version of a particular policy type.
*
* @param policyTypeId the ID of specified policy type
+ * @param versionId the version of specified policy type
*
* @return the Response object containing the results of the API operation
*/
@DELETE
- @Path("/policytypes/{policyTypeId}")
- @ApiOperation(value = "Delete all versions of a policy type",
+ @Path("/policytypes/{policyTypeId}/versions/{versionId}")
+ @ApiOperation(value = "Delete one version of a policy type",
notes = "Rule 1: pre-defined policy types cannot be deleted;"
+ "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted."
+ "The parameterizing TOSCA policies must be deleted first;",
authorizations = @Authorization(value = "basicAuth"),
tags = { "PolicyType", },
- 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 = ToscaServiceTemplate.class,
responseHeaders = {
@ResponseHeader(name = "X-MinorVersion",
description = "Used to request or communicate a MINOR version back from the client"
@@ -413,36 +458,7 @@ public class ApiRestController {
@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 deleteAllVersionsOfPolicyType(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyTypeProvider().deletePolicyTypes(policyTypeId, null)).build();
- }
-
- /**
- * Deletes specified version of a particular policy type.
- *
- * @param policyTypeId the ID of specified policy type
- * @param versionId the version of specified policy type
- *
- * @return the Response object containing the results of the API operation
- */
- @DELETE
- @Path("/policytypes/{policyTypeId}/versions/{versionId}")
- @ApiOperation(value = "Delete one version of a policy type",
- notes = "Rule 1: pre-defined policy types cannot be deleted;"
- + "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted."
- + "The parameterizing TOSCA policies must be deleted first;",
- authorizations = @Authorization(value = "basicAuth"),
- tags = { "PolicyType", },
+ },
extensions = {
@Extension(name = "interface info", properties = {
@ExtensionProperty(name = "api-version", value = "1.0.0"),
@@ -450,24 +466,6 @@ public class ApiRestController {
})
})
@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"),
@@ -478,8 +476,17 @@ public class ApiRestController {
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
@PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyTypeProvider().deletePolicyTypes(policyTypeId, versionId)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()
+ .deletePolicyType(policyTypeId, versionId);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
@@ -531,8 +538,19 @@ public class ApiRestController {
@PathParam("policyTypeVersion")
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, null, null)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ .fetchPolicies(policyTypeId, policyTypeVersion, null, null);
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
@@ -586,8 +604,19 @@ public class ApiRestController {
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,
@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 PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, policyId, null)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ .fetchPolicies(policyTypeId, policyTypeVersion, policyId, null);
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
@@ -643,13 +672,23 @@ public class ApiRestController {
@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 PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion,
- policyId, policyVersion)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ .fetchPolicies(policyTypeId, policyTypeVersion, policyId, policyVersion);
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
- * Retrieves either latest or deployed version of a particular policy depending on query parameter.
+ * Retrieves the latest version of a particular policy.
*
* @param policyTypeId the ID of specified policy type
* @param policyTypeVersion the version of specified policy type
@@ -658,9 +697,9 @@ public class ApiRestController {
* @return the Response object containing the results of the API operation
*/
@GET
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions")
- @ApiOperation(value = "Retrieve either latest or deployed version of a particular policy depending on query param",
- notes = "Returns either latest or deployed version of specified policy depending on query param",
+ @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/latest")
+ @ApiOperation(value = "Retrieve the latest version of a particular policy",
+ notes = "Returns the latest version of specified policy",
response = ToscaServiceTemplate.class,
responseHeaders = {
@ResponseHeader(name = "X-MinorVersion",
@@ -693,34 +732,41 @@ public class ApiRestController {
@ApiResponse(code = 404, message = "Resource Not Found"),
@ApiResponse(code = 500, message = "Internal Server Error")
})
- public Response getEitherLatestOrDeployedVersionOfPolicy(
+ public Response getLatestVersionOfPolicy(
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
@PathParam("policyTypeVersion")
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,
@PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
- @QueryParam("type")
- @ApiParam(value = "Version that can only be 'latest' or 'deployed'", required = true) String type,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, policyId, type)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate =
+ new PolicyProvider().fetchLatestPolicies(policyTypeId, policyTypeVersion, policyId);
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
- * Creates a new policy for a particular policy type and version.
+ * Retrieves deployed versions of a particular policy in pdp groups.
*
* @param policyTypeId the ID of specified policy type
* @param policyTypeVersion the version of specified policy type
- * @param body the body of policy following TOSCA definition
+ * @param policyId the ID of specified policy
*
* @return the Response object containing the results of the API operation
*/
- @POST
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")
- @ApiOperation(value = "Create a new policy for a policy type version",
- notes = "Client should provide TOSCA body of the new policy",
- authorizations = @Authorization(value = "basicAuth"),
- tags = { "Policy", },
- response = ToscaServiceTemplate.class,
+ @GET
+ @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/deployed")
+ @ApiOperation(value = "Retrieve deployed versions of a particular policy in pdp groups",
+ notes = "Returns deployed versions of specified policy in pdp groups",
+ response = ToscaPolicy.class, responseContainer = "List",
responseHeaders = {
@ResponseHeader(name = "X-MinorVersion",
description = "Used to request or communicate a MINOR version back from the client"
@@ -738,6 +784,8 @@ public class ApiRestController {
description = "Used to track REST transactions for logging purpose",
response = UUID.class)
},
+ authorizations = @Authorization(value = "basicAuth"),
+ tags = { "Policy", },
extensions = {
@Extension(name = "interface info", properties = {
@ExtensionProperty(name = "api-version", value = "1.0.0"),
@@ -745,45 +793,48 @@ public class ApiRestController {
})
})
@ApiResponses(value = {
- @ApiResponse(code = 400, message = "Invalid Body"),
@ApiResponse(code = 401, message = "Authentication Error"),
@ApiResponse(code = 403, message = "Authorization Error"),
@ApiResponse(code = 404, message = "Resource Not Found"),
@ApiResponse(code = 500, message = "Internal Server Error")
})
- public Response createPolicy(
+ public Response getDeployedVersionsOfPolicy(
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
@PathParam("policyTypeVersion")
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,
- @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,
- @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new PolicyProvider().createPolicy(policyTypeId, policyTypeVersion, body)).build();
+ @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
+ @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
+
+ try {
+ Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = new PolicyProvider()
+ .fetchDeployedPolicies(policyTypeId, policyTypeVersion, policyId);
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(deployedPolicies).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
- * Deletes all versions of a particular policy.
+ * Creates a new policy for a particular policy type and version.
*
* @param policyTypeId the ID of specified policy type
* @param policyTypeVersion the version of specified policy type
- * @param policyId the ID of specified policy
+ * @param body the body of policy following TOSCA definition
*
* @return the Response object containing the results of the API operation
*/
- @DELETE
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}")
- @ApiOperation(value = "Delete all versions of a policy",
- notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",
+ @POST
+ @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")
+ @ApiOperation(value = "Create a new policy for a policy type version",
+ notes = "Client should provide TOSCA body of the new policy",
authorizations = @Authorization(value = "basicAuth"),
tags = { "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 = ToscaServiceTemplate.class,
responseHeaders = {
@ResponseHeader(name = "X-MinorVersion",
description = "Used to request or communicate a MINOR version back from the client"
@@ -800,21 +851,39 @@ public class ApiRestController {
@ResponseHeader(name = "X-ONAP-RequestID",
description = "Used to track REST transactions for logging purpose",
response = UUID.class)
- }),
+ },
+ 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 = 400, message = "Invalid Body"),
@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 deleteAllVersionsOfPolicy(
+ public Response createPolicy(
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
@PathParam("policyTypeVersion")
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,
- @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 PolicyProvider().deletePolicies(policyTypeId, policyTypeVersion, policyId, null)).build();
+ @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,
+ @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ .createPolicy(policyTypeId, policyTypeVersion, body);
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.POST);
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
/**
@@ -833,14 +902,7 @@ public class ApiRestController {
notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",
authorizations = @Authorization(value = "basicAuth"),
tags = { "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 = "Resource successfully deleted, no content returned",
+ response = ToscaServiceTemplate.class,
responseHeaders = {
@ResponseHeader(name = "X-MinorVersion",
description = "Used to request or communicate a MINOR version back from the client"
@@ -857,7 +919,14 @@ public class ApiRestController {
@ResponseHeader(name = "X-ONAP-RequestID",
description = "Used to track REST transactions for logging purpose",
response = UUID.class)
- }),
+ },
+ 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 = 401, message = "Authentication Error"),
@ApiResponse(code = 403, message = "Authorization Error"),
@ApiResponse(code = 404, message = "Resource Not Found"),
@@ -871,9 +940,17 @@ public class ApiRestController {
@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 PolicyProvider().deletePolicies(policyTypeId, policyTypeVersion,
- policyId, policyVersion)).build();
+
+ try {
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ .deletePolicy(policyTypeId, policyTypeVersion, policyId, policyVersion);
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(serviceTemplate).build();
+ } catch (PfModelException | PfModelRuntimeException pfme) {
+ return addLoggingHeaders(addVersionControlHeaders(
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
+ .entity(pfme.getErrorResponse()).build();
+ }
}
private ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {
@@ -887,4 +964,68 @@ public class ApiRestController {
}
return rb.header("X-ONAP-RequestID", requestId);
}
+
+ private enum Target {
+ POLICY, POLICY_TYPE, OTHER
+ }
+
+ private enum Result {
+ SUCCESS, FAILURE
+ }
+
+ private enum HttpMethod {
+ POST, GET
+ }
+
+ private void updateApiStatisticsCounter(Target target, Result result, HttpMethod http) {
+
+ ApiStatisticsManager.updateTotalApiCallCount();
+ if (target == Target.POLICY) {
+ if (result == Result.SUCCESS) {
+ if (http == HttpMethod.GET) {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ ApiStatisticsManager.updateTotalPolicyGetCount();
+ ApiStatisticsManager.updatePolicyGetSuccessCount();
+ } else if (http == HttpMethod.POST) {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ ApiStatisticsManager.updateTotalPolicyPostCount();
+ ApiStatisticsManager.updatePolicyPostSuccessCount();
+ }
+ } else {
+ if (http == HttpMethod.GET) {
+ ApiStatisticsManager.updateApiCallFailureCount();
+ ApiStatisticsManager.updateTotalPolicyGetCount();
+ ApiStatisticsManager.updatePolicyGetFailureCount();
+ } else {
+ ApiStatisticsManager.updateApiCallFailureCount();
+ ApiStatisticsManager.updateTotalPolicyPostCount();
+ ApiStatisticsManager.updatePolicyPostFailureCount();
+ }
+ }
+ } else if (target == Target.POLICY_TYPE) {
+ if (result == Result.SUCCESS) {
+ if (http == HttpMethod.GET) {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ ApiStatisticsManager.updateTotalPolicyTypeGetCount();
+ ApiStatisticsManager.updatePolicyTypeGetSuccessCount();
+ } else if (http == HttpMethod.POST) {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ ApiStatisticsManager.updatePolicyTypePostSuccessCount();
+ ApiStatisticsManager.updatePolicyTypePostSuccessCount();
+ }
+ } else {
+ if (http == HttpMethod.GET) {
+ ApiStatisticsManager.updateApiCallFailureCount();
+ ApiStatisticsManager.updateTotalPolicyTypeGetCount();
+ ApiStatisticsManager.updatePolicyTypeGetFailureCount();
+ } else {
+ ApiStatisticsManager.updateApiCallFailureCount();
+ ApiStatisticsManager.updateTotalPolicyTypePostCount();
+ ApiStatisticsManager.updatePolicyTypePostFailureCount();
+ }
+ }
+ } else {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ }
+ }
} \ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestServer.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestServer.java
index 46ec34d7..2a7b0cef 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestServer.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestServer.java
@@ -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;
}
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java
index 8e00b436..38736e85 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java
@@ -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) {
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java
index f627493c..60d1b1f2 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java
@@ -22,8 +22,16 @@
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
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java
index 7d3e1875..2f0b127a 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java
@@ -22,8 +22,14 @@
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
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
index 690bdbd0..8ce9a499 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
@@ -22,7 +22,18 @@
package org.onap.policy.api.main.rest.provider;
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
+import java.util.List;
+import java.util.Map;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.tuple.Pair;
+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.authorative.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
/**
* Class to provide all kinds of policy operations.
@@ -31,7 +42,18 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
*/
public class PolicyProvider {
- private static final String DELETE_OK = "Successfully deleted";
+ private PolicyModelsProvider modelsProvider;
+
+ /**
+ * Default constructor.
+ */
+ public PolicyProvider() throws PfModelException {
+
+ ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
+ PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
+ modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+ modelsProvider.init();
+ }
/**
* Retrieves a list of policies matching specified ID and version of both policy type and policy.
@@ -42,11 +64,61 @@ public class PolicyProvider {
* @param policyVersion the version of policy
*
* @return the ToscaServiceTemplate object
+ *
+ * @throws PfModelException the PfModel parsing exception
*/
public ToscaServiceTemplate fetchPolicies(String policyTypeId, String policyTypeVersion,
- String policyId, String policyVersion) {
- // placeholder
- return new ToscaServiceTemplate();
+ String policyId, String policyVersion) throws PfModelException {
+
+ validatePathParam(policyTypeId, policyTypeVersion);
+ ToscaServiceTemplate serviceTemplate;
+ if (policyId == null) {
+ serviceTemplate = modelsProvider.getPolicies4PolicyType(policyTypeId, policyTypeVersion);
+ } else {
+ serviceTemplate = modelsProvider.getPolicies(policyId, policyVersion);
+ }
+ close();
+ return serviceTemplate;
+ }
+
+ /**
+ * Retrieves a list of policies with the latest versions that match specified policy type id and version.
+ *
+ * @param policyTypeId the ID of policy type
+ * @param policyTypeVersion the version of policy type
+ * @param policyId the ID of the policy
+ *
+ * @return the ToscaServiceTemplate object
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
+ public ToscaServiceTemplate fetchLatestPolicies(String policyTypeId, String policyTypeVersion,
+ String policyId) throws PfModelException {
+
+ validatePathParam(policyTypeId, policyTypeVersion);
+ ToscaServiceTemplate serviceTemplate = modelsProvider.getLatestPolicies(policyId);
+ close();
+ return serviceTemplate;
+ }
+
+ /**
+ * Retrieves a list of deployed policies in each pdp group.
+ *
+ * @param policyTypeId the ID of policy type
+ * @param policyTypeVersion the version of policy type
+ * @param policyId the ID of the policy
+ *
+ * @return a list of deployed policies in each pdp group
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
+ public Map<Pair<String, String>, List<ToscaPolicy>> fetchDeployedPolicies(
+ String policyTypeId, String policyTypeVersion, String policyId) throws PfModelException {
+
+ validatePathParam(policyTypeId, policyTypeVersion);
+ Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = modelsProvider.getDeployedPolicyList(policyId);
+ close();
+ return deployedPolicies;
}
/**
@@ -57,26 +129,93 @@ public class PolicyProvider {
* @param body the entity body of policy
*
* @return the ToscaServiceTemplate object
+ *
+ * @throws PfModelException the PfModel parsing exception
*/
public ToscaServiceTemplate createPolicy(String policyTypeId, String policyTypeVersion,
- ToscaServiceTemplate body) {
- // placeholder
- return new ToscaServiceTemplate();
+ ToscaServiceTemplate body) throws PfModelException {
+
+ validatePathParam(policyTypeId, policyTypeVersion);
+ validatePolicyTypeMatch(policyTypeId, policyTypeVersion, body);
+ ToscaServiceTemplate serviceTemplate = modelsProvider.createPolicies(body);
+ close();
+ return serviceTemplate;
}
/**
- * Deletes the policies matching specified ID and version of both policy type and policy.
+ * Deletes the policy matching specified ID and version of both policy type and policy.
*
* @param policyTypeId the ID of policy type
* @param policyTypeVersion the version of policy type
* @param policyId the ID of policy
* @param policyVersion the version of policy
*
- * @return a string message indicating the operation results
+ * @return the ToscaServiceTemplate object
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
+ public ToscaServiceTemplate deletePolicy(String policyTypeId, String policyTypeVersion,
+ String policyId, String policyVersion) throws PfModelException {
+
+ validatePathParam(policyTypeId, policyTypeVersion);
+ ToscaServiceTemplate serviceTemplate = modelsProvider.deletePolicy(policyId, policyVersion);
+ close();
+ return serviceTemplate;
+ }
+
+ /**
+ * Checks the validation of policy type info passed in as path param.
+ *
+ * @param policyTypeId the ID of policy type
+ * @param policyTypeVersion the version of policy type
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
+ private void validatePathParam(String policyTypeId, String policyTypeVersion) throws PfModelException {
+
+ // Check policy type existence
+ try {
+ modelsProvider.getPolicyTypes(policyTypeId, policyTypeVersion);
+ } catch (Exception e) {
+ throw new PfModelException(Response.Status.NOT_FOUND, "specified policy type does not exist", e);
+ }
+ }
+
+ /**
+ * Validates the match between policy type specified in path param and the one specified in type of policy.
+ *
+ * @param body the ToscaServiceTemplate to create
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
+ private void validatePolicyTypeMatch(String policyTypeId, String policyTypeVersion, ToscaServiceTemplate body)
+ throws PfModelException {
+
+ List<Map<String, ToscaPolicy>> policies = body.getToscaTopologyTemplate().getPolicies();
+ for (Map<String, ToscaPolicy> policy : policies) {
+ if (policy.size() != 1) {
+ throw new PfModelException(Response.Status.BAD_REQUEST,
+ "one policy block contains more than one policies");
+ }
+ ToscaPolicy policyContent = policy.values().iterator().next();
+ if (!policyTypeId.equalsIgnoreCase(policyContent.getType())
+ || !policyTypeVersion.equalsIgnoreCase(policyContent.getVersion())) {
+ throw new PfModelException(Response.Status.BAD_REQUEST, "policy type info does not match");
+ }
+ }
+ }
+
+ /**
+ * Closes the connection to database.
+ *
+ * @throws PfModelException the PfModel parsing exception
*/
- public String deletePolicies(String policyTypeId, String policyTypeVersion,
- 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
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java
index 5038e315..04d8a725 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java
@@ -22,7 +22,14 @@
package org.onap.policy.api.main.rest.provider;
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
+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.authorative.concepts.ToscaServiceTemplate;
/**
* Class to provide all kinds of policy type operations.
@@ -31,7 +38,18 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
*/
public class PolicyTypeProvider {
- private static final String DELETE_OK = "Successfully deleted";
+ private PolicyModelsProvider modelsProvider;
+
+ /**
+ * Default constructor.
+ */
+ public PolicyTypeProvider() throws PfModelException {
+
+ ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
+ PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
+ modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+ modelsProvider.init();
+ }
/**
* Retrieves a list of policy types matching specified policy type ID and version.
@@ -40,10 +58,31 @@ public class PolicyTypeProvider {
* @param policyTypeVersion the version of policy type
*
* @return the ToscaServiceTemplate object
+ *
+ * @throws PfModelException the PfModel parsing exception
*/
- public ToscaServiceTemplate fetchPolicyTypes(String policyTypeId, String policyTypeVersion) {
- // placeholder
- return new ToscaServiceTemplate();
+ public ToscaServiceTemplate fetchPolicyTypes(String policyTypeId, String policyTypeVersion)
+ throws PfModelException {
+
+ ToscaServiceTemplate serviceTemplate = modelsProvider.getPolicyTypes(policyTypeId, policyTypeVersion);
+ close();
+ return serviceTemplate;
+ }
+
+ /**
+ * Retrieves a list of policy types with the latest versions.
+ *
+ * @param policyTypeId the ID of policy type
+ *
+ * @return the ToscaServiceTemplate object
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
+ public ToscaServiceTemplate fetchLatestPolicyTypes(String policyTypeId) throws PfModelException {
+
+ ToscaServiceTemplate serviceTemplate = modelsProvider.getLatestPolicyTypes(policyTypeId);
+ close();
+ return serviceTemplate;
}
/**
@@ -51,23 +90,45 @@ public class PolicyTypeProvider {
*
* @param body the entity body of policy type
*
- * @return the ToscaServiceTemplate objects
+ * @return the ToscaServiceTemplate object
+ * @throws PfModelException the PfModel parsing exception
*/
- public ToscaServiceTemplate createPolicyType(ToscaServiceTemplate body) {
- // placeholder
- return new ToscaServiceTemplate();
+ public ToscaServiceTemplate createPolicyType(ToscaServiceTemplate body) throws PfModelException {
+
+ ToscaServiceTemplate serviceTemplate = modelsProvider.createPolicyTypes(body);
+ close();
+ return serviceTemplate;
}
/**
- * Delete the policy types matching specified policy type ID and version.
+ * Delete the policy type matching specified policy type ID and version.
*
* @param policyTypeId the ID of policy type
* @param policyTypeVersion the version of policy type
*
- * @return a string message indicating the operation results
+ * @return the ToscaServiceTemplate object
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
+ public ToscaServiceTemplate deletePolicyType(String policyTypeId, String policyTypeVersion)
+ throws PfModelException {
+
+ ToscaServiceTemplate serviceTemplate = modelsProvider.deletePolicyType(policyTypeId, policyTypeVersion);
+ close();
+ return serviceTemplate;
+ }
+
+ /**
+ * Closes the connection to database.
+ *
+ * @throws PfModelException the PfModel parsing exception
*/
- public String deletePolicyTypes(String policyTypeId, String policyTypeVersion) {
- // 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);
+ }
}
}
diff --git a/main/src/main/resources/META-INF/persistence.xml b/main/src/main/resources/META-INF/persistence.xml
new file mode 100644
index 00000000..81be3db9
--- /dev/null
+++ b/main/src/main/resources/META-INF/persistence.xml
@@ -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>
diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java
index 8ff2f98e..f0f971d4 100644
--- a/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java
+++ b/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java
@@ -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.
* ================================================================================
@@ -23,19 +23,29 @@
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;
+ }
}
diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java
index 184f242b..8be52455 100644
--- a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java
+++ b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java
@@ -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"));
}
}
diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java
index 71d8c357..480a5d8a 100644
--- a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java
+++ b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java
@@ -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);
diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java
index 3c8b251d..4fb588c2 100644
--- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java
+++ b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java
@@ -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,
diff --git a/main/src/test/java/org/onap/policy/api/main/exception/PolicyApiRuntimeExceptionTest.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java
index f6770b1e..8f4f9aed 100644
--- a/main/src/test/java/org/onap/policy/api/main/exception/PolicyApiRuntimeExceptionTest.java
+++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java
@@ -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.
@@ -18,26 +20,7 @@
* ============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
index 00000000..de12fca0
--- /dev/null
+++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java
@@ -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
index 00000000..11d7e404
--- /dev/null
+++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java
@@ -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
index 00000000..d60dc2e5
--- /dev/null
+++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java
@@ -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
index 00000000..23e8567f
--- /dev/null
+++ b/main/src/test/resources/META-INF/persistence.xml
@@ -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>
diff --git a/main/src/test/resources/parameters/ApiConfigParameters.json b/main/src/test/resources/parameters/ApiConfigParameters.json
index 8fae1238..c64271c7 100644
--- a/main/src/test/resources/parameters/ApiConfigParameters.json
+++ b/main/src/test/resources/parameters/ApiConfigParameters.json
@@ -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"
}
}
diff --git a/main/src/test/resources/parameters/ApiConfigParameters_Https.json b/main/src/test/resources/parameters/ApiConfigParameters_Https.json
index ec732132..878dc1ff 100644
--- a/main/src/test/resources/parameters/ApiConfigParameters_Https.json
+++ b/main/src/test/resources/parameters/ApiConfigParameters_Https.json
@@ -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"
}
}
diff --git a/main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json b/main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json
index 2d394fbc..67e461e0 100644
--- a/main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json
+++ b/main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json
@@ -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"
}
}
diff --git a/main/src/test/resources/parameters/MinimumParameters.json b/main/src/test/resources/parameters/MinimumParameters.json
index 61c6c869..2600d20f 100644
--- a/main/src/test/resources/parameters/MinimumParameters.json
+++ b/main/src/test/resources/parameters/MinimumParameters.json
@@ -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"
}
}
diff --git a/main/src/test/resources/parameters/NoParameters.json b/main/src/test/resources/parameters/NoParameters.json
index 6b0805d3..ed2fbde2 100644
--- a/main/src/test/resources/parameters/NoParameters.json
+++ b/main/src/test/resources/parameters/NoParameters.json
@@ -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/policies/vDNS.policy.guard.minmax.input.json b/main/src/test/resources/policies/vDNS.policy.guard.minmax.input.json
index c62a229a..2dbfe8ce 100644
--- a/main/src/test/resources/policies/vDNS.policy.guard.minmax.input.json
+++ b/main/src/test/resources/policies/vDNS.policy.guard.minmax.input.json
@@ -1,5 +1,4 @@
{
-{
"policy-id" : "guard.minmax.scaleout",
"contents" : {
"actor": "SO",
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
index 00000000..26f4c021
--- /dev/null
+++ b/main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.json
@@ -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
diff --git a/main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml b/main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml
index 5a093ddb..63796fa3 100644
--- a/main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml
+++ b/main/src/test/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml
@@ -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
index 00000000..95d7a53b
--- /dev/null
+++ b/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json
@@ -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
diff --git a/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml b/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml
index 699cffd7..f8e9b752 100644
--- a/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml
+++ b/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml
@@ -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