<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>
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;
}
/**
return restServerParameters;
}
+ /**
+ * Return the databaseProviderParameters of this parameter group instance.
+ *
+ * @return the databaseProviderParameters
+ */
+ public PolicyModelsProviderParameters getDatabaseProviderParameters() {
+ return databaseProviderParameters;
+ }
+
/**
* Validate the parameter group.
*
} 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;
}
}
import io.swagger.annotations.ResponseHeader;\r
import io.swagger.annotations.SecurityDefinition;\r
import io.swagger.annotations.SwaggerDefinition;\r
+import java.util.List;\r
+import java.util.Map;\r
import java.util.UUID;\r
import javax.ws.rs.Consumes;\r
import javax.ws.rs.DELETE;\r
import javax.ws.rs.Path;\r
import javax.ws.rs.PathParam;\r
import javax.ws.rs.Produces;\r
-import javax.ws.rs.QueryParam;\r
import javax.ws.rs.core.Response;\r
import javax.ws.rs.core.Response.ResponseBuilder;\r
+import org.apache.commons.lang3.tuple.Pair;\r
import org.onap.policy.api.main.rest.provider.HealthCheckProvider;\r
import org.onap.policy.api.main.rest.provider.PolicyProvider;\r
import org.onap.policy.api.main.rest.provider.PolicyTypeProvider;\r
import org.onap.policy.api.main.rest.provider.StatisticsProvider;\r
import org.onap.policy.common.endpoints.report.HealthCheckReport;\r
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;\r
+import org.onap.policy.models.base.PfModelException;\r
+import org.onap.policy.models.base.PfModelRuntimeException;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
\r
/**\r
* Class to provide REST API services.\r
})\r
public Response getHealthCheck(\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
+\r
+ updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);\r
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
.entity(new HealthCheckProvider().performHealthCheck()).build();\r
}\r
})\r
public Response getStatistics(\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
+\r
+ updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);\r
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
.entity(new StatisticsProvider().fetchCurrentStatistics()).build();\r
}\r
})\r
public Response getAllPolicyTypes(\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyTypeProvider().fetchPolicyTypes(null, null)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider().fetchPolicyTypes(null, null);\r
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
public Response getAllVersionsOfPolicyType(\r
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyTypeProvider().fetchPolicyTypes(policyTypeId, null)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()\r
+ .fetchPolicyTypes(policyTypeId, null);\r
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
@PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyTypeProvider().fetchPolicyTypes(policyTypeId, versionId)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()\r
+ .fetchPolicyTypes(policyTypeId, versionId);\r
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
public Response createPolicyType(\r
@ApiParam(value = "Entity body of policy type", required = true) ToscaServiceTemplate body,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyTypeProvider().createPolicyType(body)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider().createPolicyType(body);\r
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.POST);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.POST);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
- * Deletes all versions of a particular policy type.\r
+ * Deletes specified version of a particular policy type.\r
*\r
* @param policyTypeId the ID of specified policy type\r
+ * @param versionId the version of specified policy type\r
*\r
* @return the Response object containing the results of the API operation\r
*/\r
@DELETE\r
- @Path("/policytypes/{policyTypeId}")\r
- @ApiOperation(value = "Delete all versions of a policy type",\r
+ @Path("/policytypes/{policyTypeId}/versions/{versionId}")\r
+ @ApiOperation(value = "Delete one version of a policy type",\r
notes = "Rule 1: pre-defined policy types cannot be deleted;"\r
+ "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted."\r
+ "The parameterizing TOSCA policies must be deleted first;",\r
authorizations = @Authorization(value = "basicAuth"),\r
tags = { "PolicyType", },\r
- extensions = {\r
- @Extension(name = "interface info", properties = {\r
- @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
- @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
- })\r
- })\r
- @ApiResponses(value = {\r
- @ApiResponse(code = 204, message = "Resources successfully deleted, no content returned",\r
+ response = ToscaServiceTemplate.class,\r
responseHeaders = {\r
@ResponseHeader(name = "X-MinorVersion",\r
description = "Used to request or communicate a MINOR version back from the client"\r
@ResponseHeader(name = "X-ONAP-RequestID",\r
description = "Used to track REST transactions for logging purpose",\r
response = UUID.class)\r
- }),\r
- @ApiResponse(code = 401, message = "Authentication Error"),\r
- @ApiResponse(code = 403, message = "Authorization Error"),\r
- @ApiResponse(code = 404, message = "Resource Not Found"),\r
- @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"),\r
- @ApiResponse(code = 500, message = "Internal Server Error")\r
- })\r
- public Response deleteAllVersionsOfPolicyType(\r
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
- @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyTypeProvider().deletePolicyTypes(policyTypeId, null)).build();\r
- }\r
-\r
- /**\r
- * Deletes specified version of a particular policy type.\r
- *\r
- * @param policyTypeId the ID of specified policy type\r
- * @param versionId the version of specified policy type\r
- *\r
- * @return the Response object containing the results of the API operation\r
- */\r
- @DELETE\r
- @Path("/policytypes/{policyTypeId}/versions/{versionId}")\r
- @ApiOperation(value = "Delete one version of a policy type",\r
- notes = "Rule 1: pre-defined policy types cannot be deleted;"\r
- + "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted."\r
- + "The parameterizing TOSCA policies must be deleted first;",\r
- authorizations = @Authorization(value = "basicAuth"),\r
- tags = { "PolicyType", },\r
+ },\r
extensions = {\r
@Extension(name = "interface info", properties = {\r
@ExtensionProperty(name = "api-version", value = "1.0.0"),\r
})\r
})\r
@ApiResponses(value = {\r
- @ApiResponse(code = 204, message = "Resource successfully deleted, no content returned",\r
- responseHeaders = {\r
- @ResponseHeader(name = "X-MinorVersion",\r
- description = "Used to request or communicate a MINOR version back from the client"\r
- + " to the server, and from the server back to the client",\r
- response = String.class),\r
- @ResponseHeader(name = "X-PatchVersion",\r
- description = "Used only to communicate a PATCH version in a response for"\r
- + " troubleshooting purposes only, and will not be provided by"\r
- + " the client on request",\r
- response = String.class),\r
- @ResponseHeader(name = "X-LatestVersion",\r
- description = "Used only to communicate an API's latest version",\r
- response = String.class),\r
- @ResponseHeader(name = "X-ONAP-RequestID",\r
- description = "Used to track REST transactions for logging purpose",\r
- response = UUID.class)\r
- }),\r
@ApiResponse(code = 401, message = "Authentication Error"),\r
@ApiResponse(code = 403, message = "Authorization Error"),\r
@ApiResponse(code = 404, message = "Resource Not Found"),\r
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
@PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyTypeProvider().deletePolicyTypes(policyTypeId, versionId)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()\r
+ .deletePolicyType(policyTypeId, versionId);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
@PathParam("policyTypeVersion")\r
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, null, null)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+ .fetchPolicies(policyTypeId, policyTypeVersion, null, null);\r
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
@PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, policyId, null)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+ .fetchPolicies(policyTypeId, policyTypeVersion, policyId, null);\r
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
@PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
@PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion,\r
- policyId, policyVersion)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+ .fetchPolicies(policyTypeId, policyTypeVersion, policyId, policyVersion);\r
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
- * Retrieves either latest or deployed version of a particular policy depending on query parameter.\r
+ * Retrieves the latest version of a particular policy.\r
*\r
* @param policyTypeId the ID of specified policy type\r
* @param policyTypeVersion the version of specified policy type\r
* @return the Response object containing the results of the API operation\r
*/\r
@GET\r
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions")\r
- @ApiOperation(value = "Retrieve either latest or deployed version of a particular policy depending on query param",\r
- notes = "Returns either latest or deployed version of specified policy depending on query param",\r
+ @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/latest")\r
+ @ApiOperation(value = "Retrieve the latest version of a particular policy",\r
+ notes = "Returns the latest version of specified policy",\r
response = ToscaServiceTemplate.class,\r
responseHeaders = {\r
@ResponseHeader(name = "X-MinorVersion",\r
@ApiResponse(code = 404, message = "Resource Not Found"),\r
@ApiResponse(code = 500, message = "Internal Server Error")\r
})\r
- public Response getEitherLatestOrDeployedVersionOfPolicy(\r
+ public Response getLatestVersionOfPolicy(\r
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
@PathParam("policyTypeVersion")\r
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
@PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
- @QueryParam("type")\r
- @ApiParam(value = "Version that can only be 'latest' or 'deployed'", required = true) String type,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, policyId, type)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate =\r
+ new PolicyProvider().fetchLatestPolicies(policyTypeId, policyTypeVersion, policyId);\r
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
- * Creates a new policy for a particular policy type and version.\r
+ * Retrieves deployed versions of a particular policy in pdp groups.\r
*\r
* @param policyTypeId the ID of specified policy type\r
* @param policyTypeVersion the version of specified policy type\r
- * @param body the body of policy following TOSCA definition\r
+ * @param policyId the ID of specified policy\r
*\r
* @return the Response object containing the results of the API operation\r
*/\r
- @POST\r
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")\r
- @ApiOperation(value = "Create a new policy for a policy type version",\r
- notes = "Client should provide TOSCA body of the new policy",\r
- authorizations = @Authorization(value = "basicAuth"),\r
- tags = { "Policy", },\r
- response = ToscaServiceTemplate.class,\r
+ @GET\r
+ @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/deployed")\r
+ @ApiOperation(value = "Retrieve deployed versions of a particular policy in pdp groups",\r
+ notes = "Returns deployed versions of specified policy in pdp groups",\r
+ response = ToscaPolicy.class, responseContainer = "List",\r
responseHeaders = {\r
@ResponseHeader(name = "X-MinorVersion",\r
description = "Used to request or communicate a MINOR version back from the client"\r
description = "Used to track REST transactions for logging purpose",\r
response = UUID.class)\r
},\r
+ authorizations = @Authorization(value = "basicAuth"),\r
+ tags = { "Policy", },\r
extensions = {\r
@Extension(name = "interface info", properties = {\r
@ExtensionProperty(name = "api-version", value = "1.0.0"),\r
})\r
})\r
@ApiResponses(value = {\r
- @ApiResponse(code = 400, message = "Invalid Body"),\r
@ApiResponse(code = 401, message = "Authentication Error"),\r
@ApiResponse(code = 403, message = "Authorization Error"),\r
@ApiResponse(code = 404, message = "Resource Not Found"),\r
@ApiResponse(code = 500, message = "Internal Server Error")\r
})\r
- public Response createPolicy(\r
+ public Response getDeployedVersionsOfPolicy(\r
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
@PathParam("policyTypeVersion")\r
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
- @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,\r
- @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyProvider().createPolicy(policyTypeId, policyTypeVersion, body)).build();\r
+ @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
+ @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
+\r
+ try {\r
+ Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = new PolicyProvider()\r
+ .fetchDeployedPolicies(policyTypeId, policyTypeVersion, policyId);\r
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(deployedPolicies).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
- * Deletes all versions of a particular policy.\r
+ * Creates a new policy for a particular policy type and version.\r
*\r
* @param policyTypeId the ID of specified policy type\r
* @param policyTypeVersion the version of specified policy type\r
- * @param policyId the ID of specified policy\r
+ * @param body the body of policy following TOSCA definition\r
*\r
* @return the Response object containing the results of the API operation\r
*/\r
- @DELETE\r
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}")\r
- @ApiOperation(value = "Delete all versions of a policy",\r
- notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",\r
+ @POST\r
+ @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")\r
+ @ApiOperation(value = "Create a new policy for a policy type version",\r
+ notes = "Client should provide TOSCA body of the new policy",\r
authorizations = @Authorization(value = "basicAuth"),\r
tags = { "Policy", },\r
- extensions = {\r
- @Extension(name = "interface info", properties = {\r
- @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
- @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
- })\r
- })\r
- @ApiResponses(value = {\r
- @ApiResponse(code = 204, message = "Resources successfully deleted, no content returned",\r
+ response = ToscaServiceTemplate.class,\r
responseHeaders = {\r
@ResponseHeader(name = "X-MinorVersion",\r
description = "Used to request or communicate a MINOR version back from the client"\r
@ResponseHeader(name = "X-ONAP-RequestID",\r
description = "Used to track REST transactions for logging purpose",\r
response = UUID.class)\r
- }),\r
+ },\r
+ extensions = {\r
+ @Extension(name = "interface info", properties = {\r
+ @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
+ @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
+ })\r
+ })\r
+ @ApiResponses(value = {\r
+ @ApiResponse(code = 400, message = "Invalid Body"),\r
@ApiResponse(code = 401, message = "Authentication Error"),\r
@ApiResponse(code = 403, message = "Authorization Error"),\r
@ApiResponse(code = 404, message = "Resource Not Found"),\r
- @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"),\r
@ApiResponse(code = 500, message = "Internal Server Error")\r
})\r
- public Response deleteAllVersionsOfPolicy(\r
+ public Response createPolicy(\r
@PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
@PathParam("policyTypeVersion")\r
@ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,\r
- @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
- @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyProvider().deletePolicies(policyTypeId, policyTypeVersion, policyId, null)).build();\r
+ @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,\r
+ @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+ .createPolicy(policyTypeId, policyTypeVersion, body);\r
+ updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.POST);\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
/**\r
notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",\r
authorizations = @Authorization(value = "basicAuth"),\r
tags = { "Policy", },\r
- extensions = {\r
- @Extension(name = "interface info", properties = {\r
- @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
- @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
- })\r
- })\r
- @ApiResponses(value = {\r
- @ApiResponse(code = 204, message = "Resource successfully deleted, no content returned",\r
+ response = ToscaServiceTemplate.class,\r
responseHeaders = {\r
@ResponseHeader(name = "X-MinorVersion",\r
description = "Used to request or communicate a MINOR version back from the client"\r
@ResponseHeader(name = "X-ONAP-RequestID",\r
description = "Used to track REST transactions for logging purpose",\r
response = UUID.class)\r
- }),\r
+ },\r
+ extensions = {\r
+ @Extension(name = "interface info", properties = {\r
+ @ExtensionProperty(name = "api-version", value = "1.0.0"),\r
+ @ExtensionProperty(name = "last-mod-release", value = "Dublin")\r
+ })\r
+ })\r
+ @ApiResponses(value = {\r
@ApiResponse(code = 401, message = "Authentication Error"),\r
@ApiResponse(code = 403, message = "Authorization Error"),\r
@ApiResponse(code = 404, message = "Resource Not Found"),\r
@PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
@PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {\r
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
- .entity(new PolicyProvider().deletePolicies(policyTypeId, policyTypeVersion,\r
- policyId, policyVersion)).build();\r
+\r
+ try {\r
+ ToscaServiceTemplate serviceTemplate = new PolicyProvider()\r
+ .deletePolicy(policyTypeId, policyTypeVersion, policyId, policyVersion);\r
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
+ .entity(serviceTemplate).build();\r
+ } catch (PfModelException | PfModelRuntimeException pfme) {\r
+ return addLoggingHeaders(addVersionControlHeaders(\r
+ Response.status(pfme.getErrorResponse().getResponseCode())), requestId)\r
+ .entity(pfme.getErrorResponse()).build();\r
+ }\r
}\r
\r
private ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {\r
}\r
return rb.header("X-ONAP-RequestID", requestId);\r
}\r
+\r
+ private enum Target {\r
+ POLICY, POLICY_TYPE, OTHER\r
+ }\r
+\r
+ private enum Result {\r
+ SUCCESS, FAILURE\r
+ }\r
+\r
+ private enum HttpMethod {\r
+ POST, GET\r
+ }\r
+\r
+ private void updateApiStatisticsCounter(Target target, Result result, HttpMethod http) {\r
+\r
+ ApiStatisticsManager.updateTotalApiCallCount();\r
+ if (target == Target.POLICY) {\r
+ if (result == Result.SUCCESS) {\r
+ if (http == HttpMethod.GET) {\r
+ ApiStatisticsManager.updateApiCallSuccessCount();\r
+ ApiStatisticsManager.updateTotalPolicyGetCount();\r
+ ApiStatisticsManager.updatePolicyGetSuccessCount();\r
+ } else if (http == HttpMethod.POST) {\r
+ ApiStatisticsManager.updateApiCallSuccessCount();\r
+ ApiStatisticsManager.updateTotalPolicyPostCount();\r
+ ApiStatisticsManager.updatePolicyPostSuccessCount();\r
+ }\r
+ } else {\r
+ if (http == HttpMethod.GET) {\r
+ ApiStatisticsManager.updateApiCallFailureCount();\r
+ ApiStatisticsManager.updateTotalPolicyGetCount();\r
+ ApiStatisticsManager.updatePolicyGetFailureCount();\r
+ } else {\r
+ ApiStatisticsManager.updateApiCallFailureCount();\r
+ ApiStatisticsManager.updateTotalPolicyPostCount();\r
+ ApiStatisticsManager.updatePolicyPostFailureCount();\r
+ }\r
+ }\r
+ } else if (target == Target.POLICY_TYPE) {\r
+ if (result == Result.SUCCESS) {\r
+ if (http == HttpMethod.GET) {\r
+ ApiStatisticsManager.updateApiCallSuccessCount();\r
+ ApiStatisticsManager.updateTotalPolicyTypeGetCount();\r
+ ApiStatisticsManager.updatePolicyTypeGetSuccessCount();\r
+ } else if (http == HttpMethod.POST) {\r
+ ApiStatisticsManager.updateApiCallSuccessCount();\r
+ ApiStatisticsManager.updatePolicyTypePostSuccessCount();\r
+ ApiStatisticsManager.updatePolicyTypePostSuccessCount();\r
+ }\r
+ } else {\r
+ if (http == HttpMethod.GET) {\r
+ ApiStatisticsManager.updateApiCallFailureCount();\r
+ ApiStatisticsManager.updateTotalPolicyTypeGetCount();\r
+ ApiStatisticsManager.updatePolicyTypeGetFailureCount();\r
+ } else {\r
+ ApiStatisticsManager.updateApiCallFailureCount();\r
+ ApiStatisticsManager.updateTotalPolicyTypePostCount();\r
+ ApiStatisticsManager.updatePolicyTypePostFailureCount();\r
+ }\r
+ }\r
+ } else {\r
+ ApiStatisticsManager.updateApiCallSuccessCount();\r
+ }\r
+ }\r
}
\ No newline at end of file
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;
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;
}
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;
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.
@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"
})
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();
+ }
}
/**
@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"
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();
+ }
}
/**
@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"
@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();
+ }
}
/**
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"
})
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"
@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"),
})
})
@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"),
@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();
+ }
}
/**
@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"
})
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();
+ }
}
/**
@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"
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();
+ }
}
/**
@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"
@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();
+ }
}
/**
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"
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"
@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"),
})
})
@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"),
@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) {
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.
*/
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.
* @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;
}
/**
*
* @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;
}
/**
* @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
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.
*/
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.
* @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;
}
/**
*
* @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;
}
/**
* @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
\r
package org.onap.policy.api.main.rest.provider;\r
\r
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;\r
+import java.util.List;\r
+import java.util.Map;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.tuple.Pair;\r
+import org.onap.policy.api.main.parameters.ApiParameterGroup;\r
+import org.onap.policy.common.parameters.ParameterService;\r
+import org.onap.policy.models.base.PfModelException;\r
+import org.onap.policy.models.provider.PolicyModelsProvider;\r
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;\r
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
\r
/**\r
* Class to provide all kinds of policy operations.\r
*/\r
public class PolicyProvider {\r
\r
- private static final String DELETE_OK = "Successfully deleted";\r
+ private PolicyModelsProvider modelsProvider;\r
+\r
+ /**\r
+ * Default constructor.\r
+ */\r
+ public PolicyProvider() throws PfModelException {\r
+\r
+ ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");\r
+ PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();\r
+ modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);\r
+ modelsProvider.init();\r
+ }\r
\r
/**\r
* Retrieves a list of policies matching specified ID and version of both policy type and policy.\r
* @param policyVersion the version of policy\r
*\r
* @return the ToscaServiceTemplate object\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
*/\r
public ToscaServiceTemplate fetchPolicies(String policyTypeId, String policyTypeVersion,\r
- String policyId, String policyVersion) {\r
- // placeholder\r
- return new ToscaServiceTemplate();\r
+ String policyId, String policyVersion) throws PfModelException {\r
+\r
+ validatePathParam(policyTypeId, policyTypeVersion);\r
+ ToscaServiceTemplate serviceTemplate;\r
+ if (policyId == null) {\r
+ serviceTemplate = modelsProvider.getPolicies4PolicyType(policyTypeId, policyTypeVersion);\r
+ } else {\r
+ serviceTemplate = modelsProvider.getPolicies(policyId, policyVersion);\r
+ }\r
+ close();\r
+ return serviceTemplate;\r
+ }\r
+\r
+ /**\r
+ * Retrieves a list of policies with the latest versions that match specified policy type id and version.\r
+ *\r
+ * @param policyTypeId the ID of policy type\r
+ * @param policyTypeVersion the version of policy type\r
+ * @param policyId the ID of the policy\r
+ *\r
+ * @return the ToscaServiceTemplate object\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
+ */\r
+ public ToscaServiceTemplate fetchLatestPolicies(String policyTypeId, String policyTypeVersion,\r
+ String policyId) throws PfModelException {\r
+\r
+ validatePathParam(policyTypeId, policyTypeVersion);\r
+ ToscaServiceTemplate serviceTemplate = modelsProvider.getLatestPolicies(policyId);\r
+ close();\r
+ return serviceTemplate;\r
+ }\r
+\r
+ /**\r
+ * Retrieves a list of deployed policies in each pdp group.\r
+ *\r
+ * @param policyTypeId the ID of policy type\r
+ * @param policyTypeVersion the version of policy type\r
+ * @param policyId the ID of the policy\r
+ *\r
+ * @return a list of deployed policies in each pdp group\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
+ */\r
+ public Map<Pair<String, String>, List<ToscaPolicy>> fetchDeployedPolicies(\r
+ String policyTypeId, String policyTypeVersion, String policyId) throws PfModelException {\r
+\r
+ validatePathParam(policyTypeId, policyTypeVersion);\r
+ Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = modelsProvider.getDeployedPolicyList(policyId);\r
+ close();\r
+ return deployedPolicies;\r
}\r
\r
/**\r
* @param body the entity body of policy\r
*\r
* @return the ToscaServiceTemplate object\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
*/\r
public ToscaServiceTemplate createPolicy(String policyTypeId, String policyTypeVersion,\r
- ToscaServiceTemplate body) {\r
- // placeholder\r
- return new ToscaServiceTemplate();\r
+ ToscaServiceTemplate body) throws PfModelException {\r
+\r
+ validatePathParam(policyTypeId, policyTypeVersion);\r
+ validatePolicyTypeMatch(policyTypeId, policyTypeVersion, body);\r
+ ToscaServiceTemplate serviceTemplate = modelsProvider.createPolicies(body);\r
+ close();\r
+ return serviceTemplate;\r
}\r
\r
/**\r
- * Deletes the policies matching specified ID and version of both policy type and policy.\r
+ * Deletes the policy matching specified ID and version of both policy type and policy.\r
*\r
* @param policyTypeId the ID of policy type\r
* @param policyTypeVersion the version of policy type\r
* @param policyId the ID of policy\r
* @param policyVersion the version of policy\r
*\r
- * @return a string message indicating the operation results\r
+ * @return the ToscaServiceTemplate object\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
+ */\r
+ public ToscaServiceTemplate deletePolicy(String policyTypeId, String policyTypeVersion,\r
+ String policyId, String policyVersion) throws PfModelException {\r
+\r
+ validatePathParam(policyTypeId, policyTypeVersion);\r
+ ToscaServiceTemplate serviceTemplate = modelsProvider.deletePolicy(policyId, policyVersion);\r
+ close();\r
+ return serviceTemplate;\r
+ }\r
+\r
+ /**\r
+ * Checks the validation of policy type info passed in as path param.\r
+ *\r
+ * @param policyTypeId the ID of policy type\r
+ * @param policyTypeVersion the version of policy type\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
+ */\r
+ private void validatePathParam(String policyTypeId, String policyTypeVersion) throws PfModelException {\r
+\r
+ // Check policy type existence\r
+ try {\r
+ modelsProvider.getPolicyTypes(policyTypeId, policyTypeVersion);\r
+ } catch (Exception e) {\r
+ throw new PfModelException(Response.Status.NOT_FOUND, "specified policy type does not exist", e);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Validates the match between policy type specified in path param and the one specified in type of policy.\r
+ *\r
+ * @param body the ToscaServiceTemplate to create\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
+ */\r
+ private void validatePolicyTypeMatch(String policyTypeId, String policyTypeVersion, ToscaServiceTemplate body)\r
+ throws PfModelException {\r
+\r
+ List<Map<String, ToscaPolicy>> policies = body.getToscaTopologyTemplate().getPolicies();\r
+ for (Map<String, ToscaPolicy> policy : policies) {\r
+ if (policy.size() != 1) {\r
+ throw new PfModelException(Response.Status.BAD_REQUEST,\r
+ "one policy block contains more than one policies");\r
+ }\r
+ ToscaPolicy policyContent = policy.values().iterator().next();\r
+ if (!policyTypeId.equalsIgnoreCase(policyContent.getType())\r
+ || !policyTypeVersion.equalsIgnoreCase(policyContent.getVersion())) {\r
+ throw new PfModelException(Response.Status.BAD_REQUEST, "policy type info does not match");\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Closes the connection to database.\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
*/\r
- public String deletePolicies(String policyTypeId, String policyTypeVersion,\r
- String policyId, String policyVersion) {\r
- // placeholder\r
- return DELETE_OK;\r
+ private void close() throws PfModelException {\r
+ try {\r
+ modelsProvider.close();\r
+ } catch (Exception e) {\r
+ throw new PfModelException(\r
+ Response.Status.INTERNAL_SERVER_ERROR, "error closing connection to database", e);\r
+ }\r
}\r
}
\ No newline at end of file
\r
package org.onap.policy.api.main.rest.provider;\r
\r
-import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;\r
+import javax.ws.rs.core.Response;\r
+import org.onap.policy.api.main.parameters.ApiParameterGroup;\r
+import org.onap.policy.common.parameters.ParameterService;\r
+import org.onap.policy.models.base.PfModelException;\r
+import org.onap.policy.models.provider.PolicyModelsProvider;\r
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;\r
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
\r
/**\r
* Class to provide all kinds of policy type operations.\r
*/\r
public class PolicyTypeProvider {\r
\r
- private static final String DELETE_OK = "Successfully deleted";\r
+ private PolicyModelsProvider modelsProvider;\r
+\r
+ /**\r
+ * Default constructor.\r
+ */\r
+ public PolicyTypeProvider() throws PfModelException {\r
+\r
+ ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");\r
+ PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();\r
+ modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);\r
+ modelsProvider.init();\r
+ }\r
\r
/**\r
* Retrieves a list of policy types matching specified policy type ID and version.\r
* @param policyTypeVersion the version of policy type\r
*\r
* @return the ToscaServiceTemplate object\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
*/\r
- public ToscaServiceTemplate fetchPolicyTypes(String policyTypeId, String policyTypeVersion) {\r
- // placeholder\r
- return new ToscaServiceTemplate();\r
+ public ToscaServiceTemplate fetchPolicyTypes(String policyTypeId, String policyTypeVersion)\r
+ throws PfModelException {\r
+\r
+ ToscaServiceTemplate serviceTemplate = modelsProvider.getPolicyTypes(policyTypeId, policyTypeVersion);\r
+ close();\r
+ return serviceTemplate;\r
+ }\r
+\r
+ /**\r
+ * Retrieves a list of policy types with the latest versions.\r
+ *\r
+ * @param policyTypeId the ID of policy type\r
+ *\r
+ * @return the ToscaServiceTemplate object\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
+ */\r
+ public ToscaServiceTemplate fetchLatestPolicyTypes(String policyTypeId) throws PfModelException {\r
+\r
+ ToscaServiceTemplate serviceTemplate = modelsProvider.getLatestPolicyTypes(policyTypeId);\r
+ close();\r
+ return serviceTemplate;\r
}\r
\r
/**\r
*\r
* @param body the entity body of policy type\r
*\r
- * @return the ToscaServiceTemplate objects\r
+ * @return the ToscaServiceTemplate object\r
+ * @throws PfModelException the PfModel parsing exception\r
*/\r
- public ToscaServiceTemplate createPolicyType(ToscaServiceTemplate body) {\r
- // placeholder\r
- return new ToscaServiceTemplate();\r
+ public ToscaServiceTemplate createPolicyType(ToscaServiceTemplate body) throws PfModelException {\r
+\r
+ ToscaServiceTemplate serviceTemplate = modelsProvider.createPolicyTypes(body);\r
+ close();\r
+ return serviceTemplate;\r
}\r
\r
/**\r
- * Delete the policy types matching specified policy type ID and version.\r
+ * Delete the policy type matching specified policy type ID and version.\r
*\r
* @param policyTypeId the ID of policy type\r
* @param policyTypeVersion the version of policy type\r
*\r
- * @return a string message indicating the operation results\r
+ * @return the ToscaServiceTemplate object\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
+ */\r
+ public ToscaServiceTemplate deletePolicyType(String policyTypeId, String policyTypeVersion)\r
+ throws PfModelException {\r
+\r
+ ToscaServiceTemplate serviceTemplate = modelsProvider.deletePolicyType(policyTypeId, policyTypeVersion);\r
+ close();\r
+ return serviceTemplate;\r
+ }\r
+\r
+ /**\r
+ * Closes the connection to database.\r
+ *\r
+ * @throws PfModelException the PfModel parsing exception\r
*/\r
- public String deletePolicyTypes(String policyTypeId, String policyTypeVersion) {\r
- // placeholder\r
- return DELETE_OK;\r
+ private void close() throws PfModelException {\r
+ try {\r
+ modelsProvider.close();\r
+ } catch (Exception e) {\r
+ throw new PfModelException(\r
+ Response.Status.INTERNAL_SERVER_ERROR, "error closing connection to database", e);\r
+ }\r
}\r
}\r
--- /dev/null
+<?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>
/*-
* ============LICENSE_START=======================================================
- * ONAP Policy API
- * ================================================================================
+ * ONAP Policy API
+ * ================================================================================
* Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
package org.onap.policy.api.main.parameters;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
+
/**
* Class to hold/create all parameters for test cases.
*
*/
public class CommonTestData {
+ public static final String API_GROUP_NAME = "ApiGroup";
+
private static final String REST_SERVER_PASSWORD = "zb!XztG34";
private static final String REST_SERVER_USER = "healthcheck";
private static final int REST_SERVER_PORT = 6969;
private static final String REST_SERVER_HOST = "0.0.0.0";
private static final boolean REST_SERVER_HTTPS = false;
private static final boolean REST_SERVER_AAF = false;
- public static final String API_GROUP_NAME = "ApiGroup";
+
+ private static final String PROVIDER_GROUP_NAME = "PolicyProviderParameterGroup";
+ private static final String PROVIDER_IMPL = "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl";
+ private static final String DATABASE_URL = "jdbc:h2:mem:testdb";
+ private static final String DATABASE_USER = "policy";
+ private static final String DATABASE_PASSWORD = "P01icY";
+ private static final String PERSISTENCE_UNIT = "ToscaConceptTest";
/**
* Returns an instance of RestServerParameters for test cases.
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;
+ }
}
/*-
* ============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,
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.
@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());
@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"));
}
}
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;
@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);
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);
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);
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");
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,
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 IBM.
+ * ONAP Policy API
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.api.main.exception;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Before;
-import org.junit.Test;
-public class PolicyApiRuntimeExceptionTest {
+package org.onap.policy.api.main.rest.provider;
- private PolicyApiRuntimeException policyApiRuntimeException;
- private String message = "test exception message";
-
- @Before
- public void setUp() {
- policyApiRuntimeException = new PolicyApiRuntimeException(message);
- }
-
- @Test
- public void testContructor() {
- policyApiRuntimeException = new PolicyApiRuntimeException(message, new Exception());
- assertEquals(message, policyApiRuntimeException.getMessage());
- }
-}
+public class TestLegacyGuardPolicyProvider {}
--- /dev/null
+/*-
+ * ============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 {}
--- /dev/null
+/*-
+ * ============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 {}
--- /dev/null
+/*-
+ * ============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 {}
--- /dev/null
+<?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>
"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"
}
}
"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"
}
}
"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"
}
}
"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"
}
}
"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
-{
{
"policy-id" : "guard.minmax.scaleout",
"contents" : {
--- /dev/null
+{
+ "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
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
--- /dev/null
+{
+ "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
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
entry_schema:
type: onap.datatypes.monitoring.tca_policy
data_types:
+ -
onap.datatypes.monitoring.metricsPerEventName:
derived_from: tosca.datatypes.Root
properties:
description: Thresholds associated with eventName
entry_schema:
type: onap.datatypes.monitoring.thresholds
+ -
onap.datatypes.monitoring.tca_policy:
derived_from: tosca.datatypes.Root
properties:
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:
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
"password": "zb!XztG34",
"https": true,
"aaf": false
+ },
+ "databaseProviderParameters": {
+ "name": "PolicyProviderParameterGroup",
+ "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+ "databaseUrl": "jdbc:mariadb://localhost:3306/policy",
+ "databaseUser": "policy",
+ "databasePassword": "UDAxaWNZ",
+ "persistenceUnit": "ToscaConceptMariaDBTest"
}
}
"password": "zb!XztG34",
"https": true,
"aaf": false
+ },
+ "databaseProviderParameters": {
+ "name": "PolicyProviderParameterGroup",
+ "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
+ "databaseUrl": "jdbc:mariadb://localhost:3306/policy",
+ "databaseUser": "policy",
+ "databasePassword": "UDAxaWNZ",
+ "persistenceUnit": "ToscaConceptMariaDBTest"
}
}
\ No newline at end of file