diff options
Diffstat (limited to 'main/src')
14 files changed, 953 insertions, 566 deletions
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java index 500c5a89..0c46df4e 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java @@ -228,8 +228,8 @@ public class ApiRestController { public Response getAllPolicyTypes(
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider().fetchPolicyTypes(null, null);
+ try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(null, null);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(serviceTemplate).build();
@@ -288,9 +288,8 @@ public class ApiRestController { @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()
- .fetchPolicyTypes(policyTypeId, null);
+ try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(policyTypeId, null);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(serviceTemplate).build();
@@ -351,9 +350,8 @@ public class ApiRestController { @PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()
- .fetchPolicyTypes(policyTypeId, versionId);
+ try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(policyTypeId, versionId);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(serviceTemplate).build();
@@ -412,8 +410,8 @@ public class ApiRestController { @ApiParam(value = "Entity body of policy type", required = true) ToscaServiceTemplate body,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider().createPolicyType(body);
+ try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyTypeProvider.createPolicyType(body);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.POST);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(serviceTemplate).build();
@@ -477,9 +475,8 @@ public class ApiRestController { @PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyTypeProvider()
- .deletePolicyType(policyTypeId, versionId);
+ try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyTypeProvider.deletePolicyType(policyTypeId, versionId);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(serviceTemplate).build();
} catch (PfModelException | PfModelRuntimeException pfme) {
@@ -539,9 +536,9 @@ public class ApiRestController { @ApiParam(value = "Version of policy type", required = true) String policyTypeVersion,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyProvider()
- .fetchPolicies(policyTypeId, policyTypeVersion, null, null);
+ try (PolicyProvider policyProvider = new PolicyProvider()) {
+ ToscaServiceTemplate serviceTemplate =
+ policyProvider.fetchPolicies(policyTypeId, policyTypeVersion, null, null);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(serviceTemplate).build();
@@ -605,8 +602,8 @@ public class ApiRestController { @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ try (PolicyProvider policyProvider = new PolicyProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyProvider
.fetchPolicies(policyTypeId, policyTypeVersion, policyId, null);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
@@ -673,8 +670,8 @@ public class ApiRestController { @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ try (PolicyProvider policyProvider = new PolicyProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyProvider
.fetchPolicies(policyTypeId, policyTypeVersion, policyId, policyVersion);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
@@ -739,9 +736,9 @@ public class ApiRestController { @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
+ try (PolicyProvider policyProvider = new PolicyProvider()) {
ToscaServiceTemplate serviceTemplate =
- new PolicyProvider().fetchLatestPolicies(policyTypeId, policyTypeVersion, policyId);
+ policyProvider.fetchLatestPolicies(policyTypeId, policyTypeVersion, policyId);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(serviceTemplate).build();
@@ -805,8 +802,8 @@ public class ApiRestController { @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = new PolicyProvider()
+ try (PolicyProvider policyProvider = new PolicyProvider()) {
+ Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = policyProvider
.fetchDeployedPolicies(policyTypeId, policyTypeVersion, policyId);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
@@ -872,8 +869,8 @@ public class ApiRestController { @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId,
@ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ try (PolicyProvider policyProvider = new PolicyProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyProvider
.createPolicy(policyTypeId, policyTypeVersion, body);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
@@ -941,8 +938,8 @@ public class ApiRestController { @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
- try {
- ToscaServiceTemplate serviceTemplate = new PolicyProvider()
+ try (PolicyProvider policyProvider = new PolicyProvider()) {
+ ToscaServiceTemplate serviceTemplate = policyProvider
.deletePolicy(policyTypeId, policyTypeVersion, policyId, policyVersion);
return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
.entity(serviceTemplate).build();
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java index dbf519eb..c3e73568 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java @@ -63,61 +63,6 @@ import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; public class LegacyApiRestController { /** - * Retrieves all versions of guard policies. - * - * @return the Response object containing the results of the API operation - */ - @GET - @Path("/policytypes/onap.policy.controlloop.guard/versions/1.0.0/policies") - @ApiOperation(value = "Retrieve all versions of guard policies", - notes = "Returns a list of all versions of guard policies", - response = LegacyGuardPolicyOutput.class, responseContainer = "Map", - 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) - }, - 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 = 401, message = "Authentication Error"), - @ApiResponse(code = 403, message = "Authorization Error"), - @ApiResponse(code = 500, message = "Internal Server Error") - }) - public Response getAllGuardPolicies( - @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) { - - try { - Map<String, LegacyGuardPolicyOutput> policies = new LegacyGuardPolicyProvider() - .fetchGuardPolicy(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(); - } - } - - /** * Retrieves all versions of a particular guard policy. * * @param policyId the ID of specified guard policy @@ -164,9 +109,8 @@ public class LegacyApiRestController { @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId, @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) { - try { - Map<String, LegacyGuardPolicyOutput> policies = new LegacyGuardPolicyProvider() - .fetchGuardPolicy(policyId, null); + try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) { + Map<String, LegacyGuardPolicyOutput> policies = guardPolicyProvider.fetchGuardPolicy(policyId, null); return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) .entity(policies).build(); } catch (PfModelException | PfModelRuntimeException pfme) { @@ -225,8 +169,8 @@ public class LegacyApiRestController { @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion, @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) { - try { - Map<String, LegacyGuardPolicyOutput> policies = new LegacyGuardPolicyProvider() + try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) { + Map<String, LegacyGuardPolicyOutput> policies = guardPolicyProvider .fetchGuardPolicy(policyId, policyVersion); return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) .entity(policies).build(); @@ -284,8 +228,8 @@ public class LegacyApiRestController { @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId, @ApiParam(value = "Entity body of policy", required = true) LegacyGuardPolicyInput body) { - try { - Map<String, LegacyGuardPolicyOutput> policy = new LegacyGuardPolicyProvider().createGuardPolicy(body); + try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) { + Map<String, LegacyGuardPolicyOutput> policy = guardPolicyProvider.createGuardPolicy(body); return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) .entity(policy).build(); } catch (PfModelException | PfModelRuntimeException pfme) { @@ -345,8 +289,8 @@ public class LegacyApiRestController { @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion, @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) { - try { - Map<String, LegacyGuardPolicyOutput> policies = new LegacyGuardPolicyProvider() + try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) { + Map<String, LegacyGuardPolicyOutput> policies = guardPolicyProvider .deleteGuardPolicy(policyId, policyVersion); return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) .entity(policies).build(); @@ -358,61 +302,6 @@ public class LegacyApiRestController { } /** - * Retrieves all versions of operational policies. - * - * @return the Response object containing the results of the API operation - */ - @GET - @Path("/policytypes/onap.policy.controlloop.operational/versions/1.0.0/policies") - @ApiOperation(value = "Retrieve all versions of operational policies", - notes = "Returns a list of all versions of operational policies", - response = LegacyOperationalPolicy.class, - 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) - }, - 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 = 401, message = "Authentication Error"), - @ApiResponse(code = 403, message = "Authorization Error"), - @ApiResponse(code = 500, message = "Internal Server Error") - }) - public Response getAllOperationalPolicies( - @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) { - - try { - LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider() - .fetchOperationalPolicy(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(); - } - } - - /** * Retrieves all versions of a particular operational policy. * * @param policyId the ID of specified operational policy @@ -459,9 +348,8 @@ public class LegacyApiRestController { @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId, @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) { - try { - LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider() - .fetchOperationalPolicy(policyId, null); + try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) { + LegacyOperationalPolicy policy = operationalPolicyProvider.fetchOperationalPolicy(policyId, null); return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) .entity(policy).build(); } catch (PfModelException | PfModelRuntimeException pfme) { @@ -521,9 +409,8 @@ public class LegacyApiRestController { @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion, @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) { - try { - LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider() - .fetchOperationalPolicy(policyId, policyVersion); + try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) { + LegacyOperationalPolicy policy = operationalPolicyProvider.fetchOperationalPolicy(policyId, policyVersion); return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) .entity(policy).build(); } catch (PfModelException | PfModelRuntimeException pfme) { @@ -580,9 +467,8 @@ public class LegacyApiRestController { @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId, @ApiParam(value = "Entity body of policy", required = true) LegacyOperationalPolicy body) { - try { - LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider() - .createOperationalPolicy(body); + try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) { + LegacyOperationalPolicy policy = operationalPolicyProvider.createOperationalPolicy(body); return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) .entity(policy).build(); } catch (PfModelException | PfModelRuntimeException pfme) { @@ -643,8 +529,8 @@ public class LegacyApiRestController { @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion, @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) { - try { - LegacyOperationalPolicy policy = new LegacyOperationalPolicyProvider() + try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) { + LegacyOperationalPolicy policy = operationalPolicyProvider .deleteOperationalPolicy(policyId, policyVersion); return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId) .entity(policy).build(); diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java index bdfe4306..186ce0a3 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java @@ -22,14 +22,19 @@ package org.onap.policy.api.main.rest.provider; +import java.util.ArrayList; +import java.util.List; 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.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput; @@ -38,7 +43,7 @@ import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput; * * @author Chenfei Gao (cgao@research.att.com) */ -public class LegacyGuardPolicyProvider { +public class LegacyGuardPolicyProvider implements AutoCloseable { private PolicyModelsProvider modelsProvider; @@ -63,10 +68,7 @@ public class LegacyGuardPolicyProvider { public Map<String, LegacyGuardPolicyOutput> fetchGuardPolicy(String policyId, String policyVersion) throws PfModelException { - Map<String, LegacyGuardPolicyOutput> guardPolicies = modelsProvider.getGuardPolicy(policyId); - - close(); - return guardPolicies; + return modelsProvider.getGuardPolicy(policyId); } /** @@ -78,10 +80,7 @@ public class LegacyGuardPolicyProvider { */ public Map<String, LegacyGuardPolicyOutput> createGuardPolicy(LegacyGuardPolicyInput body) throws PfModelException { - Map<String, LegacyGuardPolicyOutput> guardPolicies = modelsProvider.createGuardPolicy(body); - - close(); - return guardPolicies; + return modelsProvider.createGuardPolicy(body); } /** @@ -95,23 +94,62 @@ public class LegacyGuardPolicyProvider { public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(String policyId, String policyVersion) throws PfModelException { - Map<String, LegacyGuardPolicyOutput> guardPolicies = modelsProvider.deleteGuardPolicy(policyId); + validateDeleteEligibility(policyId, policyVersion); - close(); - return guardPolicies; + return modelsProvider.deleteGuardPolicy(policyId); } /** - * Closes the connection to database. + * Validates whether specified policy can be deleted based on the rule that deployed policy cannot be deleted. + * + * @param policyId the ID of policy + * @param policyVersion the version of policy * * @throws PfModelException the PfModel parsing exception */ - 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); + private void validateDeleteEligibility(String policyId, String policyVersion) throws PfModelException { + + List<ToscaPolicyIdentifier> policies = new ArrayList<>(); + policies.add(new ToscaPolicyIdentifier(policyId, policyVersion)); + PdpGroupFilter pdpGroupFilter = PdpGroupFilter.builder().policyList(policies).build(); + + List<PdpGroup> pdpGroups = modelsProvider.getFilteredPdpGroups(pdpGroupFilter); + + if (!pdpGroups.isEmpty()) { + throw new PfModelException(Response.Status.CONFLICT, + constructDeleteRuleViolationMessage(policyId, policyVersion, pdpGroups)); } } + + /** + * Constructs returned message for policy delete rule violation. + * + * @param policyId the ID of policy + * @param policyVersion the version of policy + * @param pdpGroups the list of pdp groups + * + * @return the constructed message + */ + private String constructDeleteRuleViolationMessage( + String policyId, String policyVersion, List<PdpGroup> pdpGroups) { + + List<String> pdpGroupNameVersionList = new ArrayList<>(); + for (PdpGroup pdpGroup : pdpGroups) { + pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion()); + } + String deployedPdpGroups = String.join(",", pdpGroupNameVersionList); + return "policy with ID " + policyId + ":" + policyVersion + + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups; + } + + /** + * Closes the connection to database. + * + * @throws PfModelException the PfModel parsing exception + */ + @Override + public void close() throws PfModelException { + + modelsProvider.close(); + } }
\ No newline at end of file diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java index e46b4c62..ec575098 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java @@ -22,13 +22,18 @@ package org.onap.policy.api.main.rest.provider; +import java.util.ArrayList; +import java.util.List; 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.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; /** @@ -36,7 +41,7 @@ import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; * * @author Chenfei Gao (cgao@research.att.com) */ -public class LegacyOperationalPolicyProvider { +public class LegacyOperationalPolicyProvider implements AutoCloseable { private PolicyModelsProvider modelsProvider; @@ -61,10 +66,7 @@ public class LegacyOperationalPolicyProvider { public LegacyOperationalPolicy fetchOperationalPolicy(String policyId, String policyVersion) throws PfModelException { - LegacyOperationalPolicy operationalPolicy = modelsProvider.getOperationalPolicy(policyId); - - close(); - return operationalPolicy; + return modelsProvider.getOperationalPolicy(policyId); } /** @@ -76,10 +78,7 @@ public class LegacyOperationalPolicyProvider { */ public LegacyOperationalPolicy createOperationalPolicy(LegacyOperationalPolicy body) throws PfModelException { - LegacyOperationalPolicy operationalPolicy = modelsProvider.createOperationalPolicy(body); - - close(); - return operationalPolicy; + return modelsProvider.createOperationalPolicy(body); } /** @@ -93,23 +92,62 @@ public class LegacyOperationalPolicyProvider { public LegacyOperationalPolicy deleteOperationalPolicy(String policyId, String policyVersion) throws PfModelException { - LegacyOperationalPolicy operationalPolicy = modelsProvider.deleteOperationalPolicy(policyId); + validateDeleteEligibility(policyId, policyVersion); - close(); - return operationalPolicy; + return modelsProvider.deleteOperationalPolicy(policyId); } /** - * Closes the connection to database. + * Validates whether specified policy can be deleted based on the rule that deployed policy cannot be deleted. + * + * @param policyId the ID of policy + * @param policyVersion the version of policy * * @throws PfModelException the PfModel parsing exception */ - 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); + private void validateDeleteEligibility(String policyId, String policyVersion) throws PfModelException { + + List<ToscaPolicyIdentifier> policies = new ArrayList<>(); + policies.add(new ToscaPolicyIdentifier(policyId, policyVersion)); + PdpGroupFilter pdpGroupFilter = PdpGroupFilter.builder().policyList(policies).build(); + + List<PdpGroup> pdpGroups = modelsProvider.getFilteredPdpGroups(pdpGroupFilter); + + if (!pdpGroups.isEmpty()) { + throw new PfModelException(Response.Status.CONFLICT, + constructDeleteRuleViolationMessage(policyId, policyVersion, pdpGroups)); } } + + /** + * Constructs returned message for policy delete rule violation. + * + * @param policyId the ID of policy + * @param policyVersion the version of policy + * @param pdpGroups the list of pdp groups + * + * @return the constructed message + */ + private String constructDeleteRuleViolationMessage( + String policyId, String policyVersion, List<PdpGroup> pdpGroups) { + + List<String> pdpGroupNameVersionList = new ArrayList<>(); + for (PdpGroup pdpGroup : pdpGroups) { + pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion()); + } + String deployedPdpGroups = String.join(",", pdpGroupNameVersionList); + return "policy with ID " + policyId + ":" + policyVersion + + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups; + } + + /** + * Closes the connection to database. + * + * @throws PfModelException the PfModel parsing exception + */ + @Override + public void close() throws PfModelException { + + modelsProvider.close(); + } }
\ No newline at end of file diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java index 1cb3af5d..8060ee7c 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java @@ -48,7 +48,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; *
* @author Chenfei Gao (cgao@research.att.com)
*/
-public class PolicyProvider {
+public class PolicyProvider implements AutoCloseable {
private PolicyModelsProvider modelsProvider;
@@ -87,7 +87,6 @@ public class PolicyProvider { constructResourceNotFoundMessage(policyTypeId, policyTypeVersion, policyId, policyVersion));
}
- close();
return serviceTemplate;
}
@@ -115,7 +114,6 @@ public class PolicyProvider { constructResourceNotFoundMessage(policyTypeId, policyTypeVersion, policyId, null));
}
- close();
return serviceTemplate;
}
@@ -143,14 +141,13 @@ public class PolicyProvider { constructDeploymentNotFoundMessage(policyTypeId, policyTypeVersion, policyId));
}
- Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicyMap = constructDeployedPolicyMap(
- pdpGroups, policyId);
+ Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicyMap =
+ constructDeployedPolicyMap(pdpGroups, policyId);
if (deployedPolicyMap.isEmpty()) {
throw new PfModelException(Response.Status.NOT_FOUND,
constructDeploymentNotFoundMessage(policyTypeId, policyTypeVersion, policyId));
}
- close();
return deployedPolicyMap;
}
@@ -171,10 +168,7 @@ public class PolicyProvider { validatePolicyTypeExist(policyTypeId, policyTypeVersion);
validatePolicyTypeMatch(policyTypeId, policyTypeVersion, body);
- ToscaServiceTemplate serviceTemplate = modelsProvider.createPolicies(body);
-
- close();
- return serviceTemplate;
+ return modelsProvider.createPolicies(body);
}
/**
@@ -201,7 +195,6 @@ public class PolicyProvider { constructResourceNotFoundMessage(policyTypeId, policyTypeVersion, policyId, policyVersion));
}
- close();
return serviceTemplate;
}
@@ -215,10 +208,10 @@ public class PolicyProvider { */
private void validatePolicyTypeExist(String policyTypeId, String policyTypeVersion) throws PfModelException {
- try {
- modelsProvider.getPolicyTypes(policyTypeId, policyTypeVersion);
- } catch (Exception e) {
- throw new PfModelException(Response.Status.NOT_FOUND, "specified policy type does not exist", e);
+ ToscaServiceTemplate serviceTemplate = modelsProvider.getPolicyTypes(policyTypeId, policyTypeVersion);
+ if (!hasPolicyType(serviceTemplate)) {
+ throw new PfModelException(Response.Status.NOT_FOUND,
+ "policy type with ID " + policyTypeId + ":" + policyTypeVersion + " does not exist");
}
}
@@ -274,10 +267,42 @@ public class PolicyProvider { List<PdpGroup> pdpGroups = modelsProvider.getFilteredPdpGroups(pdpGroupFilter);
if (!pdpGroups.isEmpty()) {
- throw new PfModelException(Response.Status.CONFLICT, "the policy has been deployed in pdp group");
+ throw new PfModelException(Response.Status.CONFLICT,
+ constructDeleteRuleViolationMessage(policyId, policyVersion, pdpGroups));
}
}
+ /**
+ * Constructs returned message for policy delete rule violation.
+ *
+ * @param policyId the ID of policy
+ * @param policyVersion the version of policy
+ * @param pdpGroups the list of pdp groups
+ *
+ * @return the constructed message
+ */
+ private String constructDeleteRuleViolationMessage(
+ String policyId, String policyVersion, List<PdpGroup> pdpGroups) {
+
+ List<String> pdpGroupNameVersionList = new ArrayList<>();
+ for (PdpGroup pdpGroup : pdpGroups) {
+ pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion());
+ }
+ String deployedPdpGroups = String.join(",", pdpGroupNameVersionList);
+ return "policy with ID " + policyId + ":" + policyVersion
+ + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups;
+ }
+
+ /**
+ * Constructs the map of deployed pdp groups and deployed policies.
+ *
+ * @param pdpGroups the list of pdp groups that contain the specified policy
+ * @param policyId the ID of policy
+ *
+ * @return the constructed map of pdp groups and deployed policies
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
private Map<Pair<String, String>, List<ToscaPolicy>> constructDeployedPolicyMap(
List<PdpGroup> pdpGroups, String policyId) throws PfModelException {
@@ -360,16 +385,33 @@ public class PolicyProvider { }
/**
+ * Checks if service template contains any policy type.
+ *
+ * @param serviceTemplate the service template to check against
+ *
+ * @return boolean whether service template contains any policy type
+ */
+ private boolean hasPolicyType(ToscaServiceTemplate serviceTemplate) {
+
+ if (serviceTemplate.getPolicyTypes() == null) {
+ return false;
+ } else if (serviceTemplate.getPolicyTypes().isEmpty()) {
+ return false;
+ } else if (serviceTemplate.getPolicyTypes().get(0).isEmpty()) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ /**
* Closes the connection to database.
*
* @throws PfModelException the PfModel parsing exception
*/
- 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);
- }
+ @Override
+ public void close() throws PfModelException {
+
+ modelsProvider.close();
}
}
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java index 19f3a750..24b8b1bd 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java @@ -22,6 +22,7 @@ package org.onap.policy.api.main.rest.provider;
+import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Response;
import org.onap.policy.api.main.parameters.ApiParameterGroup;
@@ -40,7 +41,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; *
* @author Chenfei Gao (cgao@research.att.com)
*/
-public class PolicyTypeProvider {
+public class PolicyTypeProvider implements AutoCloseable {
private PolicyModelsProvider modelsProvider;
@@ -76,7 +77,6 @@ public class PolicyTypeProvider { constructResourceNotFoundMessage(policyTypeId, policyTypeVersion));
}
- close();
return serviceTemplate;
}
@@ -94,12 +94,11 @@ public class PolicyTypeProvider { ToscaPolicyTypeFilter policyTypeFilter = ToscaPolicyTypeFilter.builder()
.name(policyTypeId).version(ToscaPolicyTypeFilter.LATEST_VERSION).build();
ToscaServiceTemplate serviceTemplate = modelsProvider.getFilteredPolicyTypes(policyTypeFilter);
- if (serviceTemplate.getPolicyTypes().isEmpty()) {
+ if (!hasPolicyType(serviceTemplate)) {
throw new PfModelException(Response.Status.NOT_FOUND,
constructResourceNotFoundMessage(policyTypeId, null));
}
- close();
return serviceTemplate;
}
@@ -113,10 +112,7 @@ public class PolicyTypeProvider { */
public ToscaServiceTemplate createPolicyType(ToscaServiceTemplate body) throws PfModelException {
- ToscaServiceTemplate serviceTemplate = modelsProvider.createPolicyTypes(body);
-
- close();
- return serviceTemplate;
+ return modelsProvider.createPolicyTypes(body);
}
/**
@@ -136,7 +132,11 @@ public class PolicyTypeProvider { ToscaServiceTemplate serviceTemplate = modelsProvider.deletePolicyType(policyTypeId, policyTypeVersion);
- close();
+ if (!hasPolicyType(serviceTemplate)) {
+ throw new PfModelException(Response.Status.NOT_FOUND,
+ constructResourceNotFoundMessage(policyTypeId, policyTypeVersion));
+ }
+
return serviceTemplate;
}
@@ -156,11 +156,32 @@ public class PolicyTypeProvider { List<ToscaPolicy> policies = modelsProvider.getFilteredPolicyList(policyFilter);
if (!policies.isEmpty()) {
throw new PfModelException(Response.Status.CONFLICT,
- "the policy type has been parameterized by at least one policies");
+ constructDeleteRuleViolationMessage(policyTypeId, policyTypeVersion, policies));
}
}
/**
+ * Constructs returned message for policy type delete rule violation.
+ *
+ * @param policyTypeId the ID of policy type
+ * @param policyTypeVersion the version of policy type
+ * @param policies the list of policies that parameterizes specified policy type
+ *
+ * @return the constructed message
+ */
+ private String constructDeleteRuleViolationMessage(
+ String policyTypeId, String policyTypeVersion, List<ToscaPolicy> policies) {
+
+ List<String> policyNameVersionList = new ArrayList<>();
+ for (ToscaPolicy policy : policies) {
+ policyNameVersionList.add(policy.getName() + ":" + policy.getVersion());
+ }
+ String parameterizedPolicies = String.join(",", policyNameVersionList);
+ return "policy type with ID " + policyTypeId + ":" + policyTypeVersion
+ + " cannot be deleted as it is parameterized by policies " + parameterizedPolicies;
+ }
+
+ /**
* Constructs returned message for not found resource.
*
* @param policyTypeId the ID of policy type
@@ -198,13 +219,9 @@ public class PolicyTypeProvider { *
* @throws PfModelException the PfModel parsing exception
*/
- private void close() throws PfModelException {
+ @Override + public void close() throws PfModelException {
- try {
- modelsProvider.close();
- } catch (Exception e) {
- throw new PfModelException(
- Response.Status.INTERNAL_SERVER_ERROR, "error closing connection to database", e);
- }
+ modelsProvider.close();
}
}
diff --git a/main/src/main/resources/META-INF/persistence.xml b/main/src/main/resources/META-INF/persistence.xml index 8812ebf6..7bda7dab 100644 --- a/main/src/main/resources/META-INF/persistence.xml +++ b/main/src/main/resources/META-INF/persistence.xml @@ -2,7 +2,6 @@ <!-- ============LICENSE_START======================================================= Copyright (C) 2019 Nordix Foundation. - 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. @@ -21,30 +20,7 @@ --> <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> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpGroup</class> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup</class> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdp</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"> + <persistence-unit name="PolicyMariaDb" transaction-type="RESOURCE_LOCAL"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <class>org.onap.policy.models.dao.converters.CDataConditioner</class> @@ -58,25 +34,13 @@ <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.jdbc.url" value="jdbc:mariadb://policydb:3306/policy" /> + <property name="javax.persistence.jdbc.user" value="policy_user" /> + <property name="javax.persistence.jdbc.password" value="policy_user" /> <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="create-or-extend-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> <property name="eclipselink.logging.level" value="INFO" /> </properties> </persistence-unit> -</persistence> +</persistence>
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java index 08f7fecd..085255f3 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java @@ -22,20 +22,26 @@ package org.onap.policy.api.main.rest.provider; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertTrue; import java.util.Base64; -import org.junit.Before; +import java.util.Map; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.api.main.parameters.ApiParameterGroup; import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.provider.PolicyModelsProviderParameters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput; +import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput; /** * This class performs unit test of {@link LegacyGuardPolicyProvider} @@ -44,38 +50,105 @@ import org.slf4j.LoggerFactory; */ public class TestLegacyGuardPolicyProvider { - private static final Logger LOGGER = LoggerFactory.getLogger(TestPolicyProvider.class); + private static LegacyGuardPolicyProvider guardPolicyProvider; + private static PolicyModelsProviderParameters providerParams; + private static ApiParameterGroup apiParamGroup; + private static StandardCoder standardCoder; - private LegacyGuardPolicyProvider guardPolicyProvider; + private static final String POLICY_RESOURCE = "policies/vDNS.policy.guard.frequency.input.json"; /** - * Initialize parameters. + * Initializes parameters. + * + * @throws PfModelException the PfModel parsing exception */ - @Before - public void setupParameters() throws PfModelException { - - PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); - parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); - parameters.setDatabaseUser("policy"); - parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); - parameters.setPersistenceUnit("ToscaConceptTest"); - ApiParameterGroup paramGroup = new ApiParameterGroup("ApiGroup", null, parameters); - ParameterService.register(paramGroup, true); + @BeforeClass + public static void setupParameters() throws PfModelException { + + standardCoder = new StandardCoder(); + providerParams = new PolicyModelsProviderParameters(); + providerParams.setDatabaseUrl("jdbc:h2:mem:testdb"); + providerParams.setDatabaseUser("policy"); + providerParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + providerParams.setPersistenceUnit("ToscaConceptTest"); + apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams); + ParameterService.register(apiParamGroup, true); guardPolicyProvider = new LegacyGuardPolicyProvider(); } + /** + * Closes up DB connections and deregisters API parameter group. + * + * @throws PfModelException the PfModel parsing exception + */ + @AfterClass + public static void tearDown() throws PfModelException { + + guardPolicyProvider.close(); + ParameterService.deregister(apiParamGroup); + } + + @Test public void testFetchGuardPolicy() { + assertThatThrownBy(() -> { + guardPolicyProvider.fetchGuardPolicy("dummy", null); + }).hasMessage("no policy found for policy ID: dummy"); + + assertThatThrownBy(() -> { + guardPolicyProvider.fetchGuardPolicy("dummy", "dummy"); + }).hasMessage("no policy found for policy ID: dummy"); } @Test public void testCreateGuardPolicy() { + assertThatCode(() -> { + String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); + LegacyGuardPolicyInput policyToCreate = standardCoder.decode(policyString, LegacyGuardPolicyInput.class); + Map<String, LegacyGuardPolicyOutput> createdPolicy = guardPolicyProvider.createGuardPolicy(policyToCreate); + assertNotNull(createdPolicy); + assertFalse(createdPolicy.isEmpty()); + assertTrue(createdPolicy.containsKey("guard.frequency.scaleout")); + assertEquals("onap.policies.controlloop.guard.FrequencyLimiter", + createdPolicy.get("guard.frequency.scaleout").getType()); + assertEquals("1.0.0", createdPolicy.get("guard.frequency.scaleout").getVersion()); + }).doesNotThrowAnyException(); } @Test public void testDeleteGuardPolicy() { + assertThatThrownBy(() -> { + guardPolicyProvider.deleteGuardPolicy("dummy", null); + }).hasMessage("version is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + guardPolicyProvider.deleteGuardPolicy("dummy", "dummy"); + }).hasMessage("no policy found for policy ID: dummy"); + + assertThatCode(() -> { + String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); + LegacyGuardPolicyInput policyToCreate = standardCoder.decode(policyString, LegacyGuardPolicyInput.class); + Map<String, LegacyGuardPolicyOutput> createdPolicy = guardPolicyProvider.createGuardPolicy(policyToCreate); + assertNotNull(createdPolicy); + assertFalse(createdPolicy.isEmpty()); + }).doesNotThrowAnyException(); + + assertThatCode(() -> { + Map<String, LegacyGuardPolicyOutput> deletedPolicy = guardPolicyProvider + .deleteGuardPolicy("guard.frequency.scaleout", "1.0.0"); + assertNotNull(deletedPolicy); + assertFalse(deletedPolicy.isEmpty()); + assertTrue(deletedPolicy.containsKey("guard.frequency.scaleout")); + assertEquals("onap.policies.controlloop.guard.FrequencyLimiter", + deletedPolicy.get("guard.frequency.scaleout").getType()); + assertEquals("1.0.0", deletedPolicy.get("guard.frequency.scaleout").getVersion()); + }).doesNotThrowAnyException(); + + assertThatThrownBy(() -> { + guardPolicyProvider.deleteGuardPolicy("guard.frequency.scaleout", "1.0.0"); + }).hasMessage("no policy found for policy ID: guard.frequency.scaleout"); } } diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java index 86124c74..e9adae7c 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java @@ -22,20 +22,23 @@ package org.onap.policy.api.main.rest.provider; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertTrue; import java.util.Base64; -import org.junit.Before; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.api.main.parameters.ApiParameterGroup; import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.provider.PolicyModelsProviderParameters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; /** * This class performs unit test of {@link LegacyOperationalPolicyProvider} @@ -44,38 +47,99 @@ import org.slf4j.LoggerFactory; */ public class TestLegacyOperationalPolicyProvider { - private static final Logger LOGGER = LoggerFactory.getLogger(TestPolicyProvider.class); + private static LegacyOperationalPolicyProvider operationalPolicyProvider; + private static PolicyModelsProviderParameters providerParams; + private static ApiParameterGroup apiParamGroup; + private static StandardCoder standardCoder; - private LegacyOperationalPolicyProvider operationalPolicyProvider; + private static final String POLICY_RESOURCE = "policies/vCPE.policy.operational.input.json"; /** - * Initialize parameters. + * Initializes parameters. + * + * @throws PfModelException the PfModel parsing exception */ - @Before - public void setupParameters() throws PfModelException { - - PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); - parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); - parameters.setDatabaseUser("policy"); - parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); - parameters.setPersistenceUnit("ToscaConceptTest"); - ApiParameterGroup paramGroup = new ApiParameterGroup("ApiGroup", null, parameters); - ParameterService.register(paramGroup, true); + @BeforeClass + public static void setupParameters() throws PfModelException { + + standardCoder = new StandardCoder(); + providerParams = new PolicyModelsProviderParameters(); + providerParams.setDatabaseUrl("jdbc:h2:mem:testdb"); + providerParams.setDatabaseUser("policy"); + providerParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + providerParams.setPersistenceUnit("ToscaConceptTest"); + apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams); + ParameterService.register(apiParamGroup, true); operationalPolicyProvider = new LegacyOperationalPolicyProvider(); } + /** + * Closes up DB connections and deregisters API parameter group. + * + * @throws PfModelException the PfModel parsing exception + */ + @AfterClass + public static void tearDown() throws PfModelException { + + operationalPolicyProvider.close(); + ParameterService.deregister(apiParamGroup); + } + @Test public void testFetchOperationalPolicy() { + assertThatThrownBy(() -> { + operationalPolicyProvider.fetchOperationalPolicy("dummy", null); + }).hasMessage("no policy found for policy ID: dummy"); + + assertThatThrownBy(() -> { + operationalPolicyProvider.fetchOperationalPolicy("dummy", "dummy"); + }).hasMessage("no policy found for policy ID: dummy"); } @Test public void testCreateOperationalPolicy() { + assertThatCode(() -> { + String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); + LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class); + LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate); + assertNotNull(createdPolicy); + assertEquals("operational.restart", createdPolicy.getPolicyId()); + assertTrue(createdPolicy.getContent() + .startsWith("controlLoop%3A%0A%20%20version%3A%202.0.0%0A%20%20")); + }).doesNotThrowAnyException(); } @Test public void testDeleteOperationalPolicy() { + assertThatThrownBy(() -> { + operationalPolicyProvider.deleteOperationalPolicy("dummy", null); + }).hasMessage("version is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + operationalPolicyProvider.deleteOperationalPolicy("dummy", "dummy"); + }).hasMessage("no policy found for policy ID: dummy"); + + assertThatCode(() -> { + String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); + LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class); + LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate); + assertNotNull(createdPolicy); + }).doesNotThrowAnyException(); + + assertThatCode(() -> { + LegacyOperationalPolicy deletedPolicy = operationalPolicyProvider + .deleteOperationalPolicy("operational.restart", "1.0.0"); + assertNotNull(deletedPolicy); + assertEquals("operational.restart", deletedPolicy.getPolicyId()); + assertTrue(deletedPolicy.getContent() + .startsWith("controlLoop%3A%0A%20%20version%3A%202.0.0%0A%20%20")); + }).doesNotThrowAnyException(); + + assertThatThrownBy(() -> { + operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1.0.0"); + }).hasMessage("no policy found for policy ID: operational.restart"); } } diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java index eeb4dbae..7720575a 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java @@ -22,20 +22,21 @@ package org.onap.policy.api.main.rest.provider; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertFalse; import java.util.Base64; -import org.junit.Before; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.api.main.parameters.ApiParameterGroup; import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.provider.PolicyModelsProviderParameters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; /** * This class performs unit test of {@link PolicyProvider} @@ -44,49 +45,141 @@ import org.slf4j.LoggerFactory; */ public class TestPolicyProvider { - private static final Logger LOGGER = LoggerFactory.getLogger(TestPolicyProvider.class); + private static PolicyProvider policyProvider; + private static PolicyTypeProvider policyTypeProvider; + private static PolicyModelsProviderParameters providerParams; + private static ApiParameterGroup apiParamGroup; + private static StandardCoder standardCoder; - private PolicyProvider policyProvider; + private static final String POLICY_RESOURCE = "policies/vCPE.policy.monitoring.input.tosca.json"; + private static final String POLICY_TYPE_RESOURCE = "policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json"; + private static final String POLICY_RESOURCE_WITH_BAD_POLICYTYPE_ID = "policies/vCPE.policy.bad.policytypeid.json"; + private static final String POLICY_RESOURCE_WITH_BAD_POLICYTYPE_VERSION = + "policies/vCPE.policy.bad.policytypeversion.json"; /** - * Initialize parameters. + * Initializes parameters. + * + * @throws PfModelException the PfModel parsing exception */ - @Before - public void setupParameters() throws PfModelException { - - PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); - parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); - parameters.setDatabaseUser("policy"); - parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); - parameters.setPersistenceUnit("ToscaConceptTest"); - ApiParameterGroup paramGroup = new ApiParameterGroup("ApiGroup", null, parameters); - ParameterService.register(paramGroup, true); + @BeforeClass + public static void setupParameters() throws PfModelException { + + standardCoder = new StandardCoder(); + providerParams = new PolicyModelsProviderParameters(); + providerParams.setDatabaseUrl("jdbc:h2:mem:testdb"); + providerParams.setDatabaseUser("policy"); + providerParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + providerParams.setPersistenceUnit("ToscaConceptTest"); + apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams); + ParameterService.register(apiParamGroup, true); + policyTypeProvider = new PolicyTypeProvider(); policyProvider = new PolicyProvider(); - System.out.println("xxxx"); + } + + /** + * Closes up DB connections and deregisters API parameter group. + * + * @throws PfModelException the PfModel parsing exception + */ + @AfterClass + public static void tearDown() throws PfModelException { + + policyTypeProvider.close(); + policyProvider.close(); + ParameterService.deregister(apiParamGroup); } @Test public void testFetchPolicies() { + assertThatThrownBy(() -> { + policyProvider.fetchPolicies("dummy", "dummy", null, null); + }).hasMessage("policy with ID null:null and type dummy:dummy does not exist"); + + assertThatThrownBy(() -> { + policyProvider.fetchPolicies("dummy", "dummy", "dummy", null); + }).hasMessage("policy with ID dummy:null and type dummy:dummy does not exist"); + + assertThatThrownBy(() -> { + policyProvider.fetchPolicies("dummy", "dummy", "dummy", "dummy"); + }).hasMessage("policy with ID dummy:dummy and type dummy:dummy does not exist"); } @Test public void testFetchLatestPolicies() { + assertThatThrownBy(() -> { + policyProvider.fetchLatestPolicies("dummy", "dummy", "dummy"); + }).hasMessage("policy with ID dummy:null and type dummy:dummy does not exist"); } @Test public void testFetchDeployedPolicies() { + assertThatThrownBy(() -> { + policyProvider.fetchDeployedPolicies("dummy", "dummy", "dummy"); + }).hasMessage("could not find policy with ID dummy and type dummy:dummy deployed in any pdp group"); } @Test public void testCreatePolicy() { + assertThatThrownBy(() -> { + policyProvider.createPolicy("dummy", "dummy", new ToscaServiceTemplate()); + }).hasMessage("policy type with ID dummy:dummy does not exist"); + + assertThatCode(() -> { + String policyTypeString = ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE); + ToscaServiceTemplate policyTypeServiceTemplate = + standardCoder.decode(policyTypeString, ToscaServiceTemplate.class); + policyTypeProvider.createPolicyType(policyTypeServiceTemplate); + }).doesNotThrowAnyException(); + + assertThatThrownBy(() -> { + String badPolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_WITH_BAD_POLICYTYPE_ID); + ToscaServiceTemplate badPolicyServiceTemplate = + standardCoder.decode(badPolicyString, ToscaServiceTemplate.class); + policyProvider.createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", + badPolicyServiceTemplate); + }).hasMessage("policy type id does not match"); + + assertThatThrownBy(() -> { + String badPolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_WITH_BAD_POLICYTYPE_VERSION); + ToscaServiceTemplate badPolicyServiceTemplate = + standardCoder.decode(badPolicyString, ToscaServiceTemplate.class); + policyProvider.createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", + badPolicyServiceTemplate); + }).hasMessage("policy type version does not match"); + + assertThatCode(() -> { + String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); + ToscaServiceTemplate policyServiceTemplate = + standardCoder.decode(policyString, ToscaServiceTemplate.class); + ToscaServiceTemplate serviceTemplate = policyProvider + .createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + assertFalse(serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()); + }).doesNotThrowAnyException(); } @Test public void testDeletePolicy() { + assertThatThrownBy(() -> { + policyProvider.deletePolicy("dummy", "dummy", "dummy", "dummy"); + }).hasMessage("policy with ID dummy:dummy and type dummy:dummy does not exist"); + + assertThatCode(() -> { + ToscaServiceTemplate serviceTemplate = policyProvider.deletePolicy( + "onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", "onap.restart.tca", "1.0.0"); + assertFalse(serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()); + }).doesNotThrowAnyException(); + + String exceptionMessage = "policy with ID onap.restart.tca:1.0.0 and type " + + "onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 does not exist"; + assertThatThrownBy(() -> { + policyProvider.deletePolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", + "onap.restart.tca", "1.0.0"); + }).hasMessage(exceptionMessage); } } diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java index 4c3f23b3..76825b20 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java @@ -22,20 +22,21 @@ package org.onap.policy.api.main.rest.provider; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertFalse; import java.util.Base64; -import org.junit.Before; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.api.main.parameters.ApiParameterGroup; import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.provider.PolicyModelsProviderParameters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; /** * This class performs unit test of {@link PolicyTypeProvider} @@ -44,43 +45,116 @@ import org.slf4j.LoggerFactory; */ public class TestPolicyTypeProvider { - private static final Logger LOGGER = LoggerFactory.getLogger(TestPolicyTypeProvider.class); + private static PolicyTypeProvider policyTypeProvider; + private static PolicyProvider policyProvider; + private static PolicyModelsProviderParameters providerParams; + private static ApiParameterGroup apiParamGroup; + private static StandardCoder standardCoder; - private PolicyTypeProvider policyTypeProvider; + private static final String POLICY_RESOURCE = "policies/vCPE.policy.monitoring.input.tosca.json"; + private static final String POLICY_TYPE_RESOURCE = "policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json"; /** - * Initialize parameters. + * Initializes parameters. + * + * @throws PfModelException the PfModel parsing exception */ - @Before - public void setupParameters() throws PfModelException { - - PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); - parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); - parameters.setDatabaseUser("policy"); - parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); - parameters.setPersistenceUnit("ToscaConceptTest"); - ApiParameterGroup paramGroup = new ApiParameterGroup("ApiGroup", null, parameters); - ParameterService.register(paramGroup, true); + @BeforeClass + public static void setupParameters() throws PfModelException { + + standardCoder = new StandardCoder(); + providerParams = new PolicyModelsProviderParameters(); + providerParams.setDatabaseUrl("jdbc:h2:mem:testdb"); + providerParams.setDatabaseUser("policy"); + providerParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + providerParams.setPersistenceUnit("ToscaConceptTest"); + apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams); + ParameterService.register(apiParamGroup, true); policyTypeProvider = new PolicyTypeProvider(); + policyProvider = new PolicyProvider(); + } + + /** + * Closes up DB connections and deregisters API parameter group. + * + * @throws PfModelException the PfModel parsing exception + */ + @AfterClass + public static void tearDown() throws PfModelException { + + policyTypeProvider.close(); + policyProvider.close(); + ParameterService.deregister(apiParamGroup); } @Test public void testFetchPolicyTypes() { + assertThatCode(() -> { + ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(null, null); + assertFalse(serviceTemplate.getPolicyTypes().isEmpty()); + }).doesNotThrowAnyException(); + + assertThatThrownBy(() -> { + policyTypeProvider.fetchPolicyTypes("dummy", null); + }).hasMessage("policy type with ID dummy:null does not exist"); + + assertThatThrownBy(() -> { + policyTypeProvider.fetchPolicyTypes("dummy", "dummy"); + }).hasMessage("policy type with ID dummy:dummy does not exist"); } @Test public void testFetchLatestPolicyTypes() { + assertThatThrownBy(() -> { + policyTypeProvider.fetchLatestPolicyTypes("dummy"); + }).hasMessage("policy type with ID dummy:null does not exist"); } @Test public void testCreatePolicyType() { + assertThatCode(() -> { + String policyTypeString = ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE); + ToscaServiceTemplate policyTypeServiceTemplate = + standardCoder.decode(policyTypeString, ToscaServiceTemplate.class); + ToscaServiceTemplate serviceTemplate = policyTypeProvider.createPolicyType(policyTypeServiceTemplate); + assertFalse(serviceTemplate.getPolicyTypes().get(0).isEmpty()); + }).doesNotThrowAnyException(); } @Test public void testDeletePolicyType() { + assertThatCode(() -> { + String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); + ToscaServiceTemplate policyServiceTemplate = + standardCoder.decode(policyString, ToscaServiceTemplate.class); + policyProvider.createPolicy( + "onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + }).doesNotThrowAnyException(); + + String exceptionMessage = "policy type with ID onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 " + + "cannot be deleted as it is parameterized by policies onap.restart.tca:1.0.0"; + assertThatThrownBy(() -> { + policyTypeProvider.deletePolicyType("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0"); + }).hasMessage(exceptionMessage); + + assertThatCode(() -> { + ToscaServiceTemplate serviceTemplate = policyProvider.deletePolicy( + "onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", "onap.restart.tca", "1.0.0"); + assertFalse(serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()); + }).doesNotThrowAnyException(); + + assertThatCode(() -> { + ToscaServiceTemplate serviceTemplate = policyTypeProvider.deletePolicyType( + "onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0"); + assertFalse(serviceTemplate.getPolicyTypes().get(0).isEmpty()); + }).doesNotThrowAnyException(); + + assertThatThrownBy(() -> { + policyTypeProvider.deletePolicyType("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0"); + }).hasMessage("policy type with ID onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 does not exist"); } } diff --git a/main/src/test/resources/policies/vCPE.policy.bad.policytypeid.json b/main/src/test/resources/policies/vCPE.policy.bad.policytypeid.json new file mode 100644 index 00000000..4eb84aa5 --- /dev/null +++ b/main/src/test/resources/policies/vCPE.policy.bad.policytypeid.json @@ -0,0 +1,50 @@ +{ + "tosca_definitions_version": "tosca_simple_yaml_1_0_0", + "topology_template": { + "policies": [ + { + "onap.restart.tca": { + "type": "onap.policies.monitoring.cdap.tca.hi.lo.appxxx", + "version": "1.0.0", + "metadata": { + "policy-id": "onap.restart.tca" + }, + "properties": { + "tca_policy" : { + "domain": "measurementsForVfScaling", + "metricsPerEventName": [ + { + "eventName": "Measurement_vGMUX", + "controlLoopSchemaType": "VNF", + "policyScope": "DCAE", + "policyName": "DCAE.Config_tca-hi-lo", + "policyVersion": "v0.0.1", + "thresholds": [ + { + "closedLoopControlName": "ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e", + "version": "1.0.2", + "fieldPath": "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value", + "thresholdValue": 0, + "direction": "EQUAL", + "severity": "MAJOR", + "closedLoopEventStatus": "ABATED" + }, + { + "closedLoopControlName": "ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e", + "version": "1.0.2", + "fieldPath": "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value", + "thresholdValue": 0, + "direction": "GREATER", + "severity": "CRITICAL", + "closedLoopEventStatus": "ONSET" + } + ] + } + ] + } + } + } + } + ] + } +}
\ No newline at end of file diff --git a/main/src/test/resources/policies/vCPE.policy.bad.policytypeversion.json b/main/src/test/resources/policies/vCPE.policy.bad.policytypeversion.json new file mode 100644 index 00000000..638a4e1d --- /dev/null +++ b/main/src/test/resources/policies/vCPE.policy.bad.policytypeversion.json @@ -0,0 +1,51 @@ +{ + "tosca_definitions_version": "tosca_simple_yaml_1_0_0", + "topology_template": { + "policies": [ + { + "onap.restart.tca": { + "type": "onap.policies.monitoring.cdap.tca.hi.lo.app", + "version": "1.0.0", + "typeVersion": "2.0.0", + "metadata": { + "policy-id": "onap.restart.tca" + }, + "properties": { + "tca_policy" : { + "domain": "measurementsForVfScaling", + "metricsPerEventName": [ + { + "eventName": "Measurement_vGMUX", + "controlLoopSchemaType": "VNF", + "policyScope": "DCAE", + "policyName": "DCAE.Config_tca-hi-lo", + "policyVersion": "v0.0.1", + "thresholds": [ + { + "closedLoopControlName": "ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e", + "version": "1.0.2", + "fieldPath": "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value", + "thresholdValue": 0, + "direction": "EQUAL", + "severity": "MAJOR", + "closedLoopEventStatus": "ABATED" + }, + { + "closedLoopControlName": "ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e", + "version": "1.0.2", + "fieldPath": "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value", + "thresholdValue": 0, + "direction": "GREATER", + "severity": "CRITICAL", + "closedLoopEventStatus": "ONSET" + } + ] + } + ] + } + } + } + } + ] + } +}
\ No newline at end of file diff --git a/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json b/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json index 292c632c..1d1a4d64 100644 --- a/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json +++ b/main/src/test/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.json @@ -1,223 +1,223 @@ { - "tosca_definitions_version": "tosca_simple_yaml_1_0_0", - "policy_types": [ - { - "onap.policies.Monitoring": { - "derived_from": "tosca.policies.Root", - "description": "a base policy type for all policies that governs monitoring provisioning" - } - }, - { - "onap.policies.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" + "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" } - } - } - } - } - ], - "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.policies.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" + } + } + } } - } } - } - }, - { - "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" + ], + "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" + } + } } - } - } - } - }, - { - "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 |