diff options
author | Jim Hahn <jrh3@att.com> | 2019-04-23 11:43:50 -0400 |
---|---|---|
committer | Jim Hahn <jrh3@att.com> | 2019-04-23 12:41:54 -0400 |
commit | b13e905e3de91ac7a018f61a95064c170821329e (patch) | |
tree | 2b88ea1e8b876f935fc28aae340ca7ea33686607 | |
parent | 4ca155ec2ca6663826d749c7443b0249e703323e (diff) |
Return appropriate HTTP status code
Return 404 instead of 500 when items are not found. Bubble up other
HTTP error codes instead of changing them all to 500.
Change-Id: Ib614bb83f28cfb1ce2384679398f0a45058fc455
Issue-ID: POLICY-1686
Signed-off-by: Jim Hahn <jrh3@att.com>
15 files changed, 351 insertions, 375 deletions
diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpModifyRequestMap.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpModifyRequestMap.java index 04bab743..3f0b5c11 100644 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpModifyRequestMap.java +++ b/main/src/main/java/org/onap/policy/pap/main/comm/PdpModifyRequestMap.java @@ -221,7 +221,7 @@ public class PdpModifyRequestMap { * @param pdpName name of the PDP to be removed * @return {@code true} if the PDP was removed from a group, {@code false} if it was * not assigned to a group - * @throws PfModelException if an error occurs + * @throws PfModelException if an error occurred */ public boolean removeFromGroups(String pdpName) throws PfModelException { diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeleteControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeleteControllerV1.java index 08781857..ad8b5081 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeleteControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeleteControllerV1.java @@ -35,15 +35,19 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; -import org.apache.commons.lang3.tuple.Pair; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; import org.onap.policy.pap.main.rest.PapRestControllerV1; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Class to provide REST end points for PAP component to delete a PDP group. */ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { + private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeleteControllerV1.class); private final PdpGroupDeleteProvider provider = new PdpGroupDeleteProvider(); @@ -82,10 +86,18 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { public Response deleteGroup(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, @ApiParam(value = "PDP Group Name", required = true) @PathParam("name") String groupName) { - Pair<Status, PdpGroupDeleteResponse> pair = provider.deleteGroup(groupName); - - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); + try { + provider.deleteGroup(groupName); + return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId) + .entity(new PdpGroupDeleteResponse()).build(); + + } catch (PfModelException | PfModelRuntimeException e) { + logger.warn("delete group failed", e); + PdpGroupDeleteResponse resp = new PdpGroupDeleteResponse(); + resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); + return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), + requestId).entity(resp).build(); + } } /** @@ -123,11 +135,18 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { public Response deletePolicy(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, @ApiParam(value = "PDP Policy Name", required = true) @PathParam("name") String policyName) { - Pair<Status, PdpGroupDeleteResponse> pair = - provider.undeploy(new ToscaPolicyIdentifierOptVersion(policyName, null)); - - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); + try { + provider.undeploy(new ToscaPolicyIdentifierOptVersion(policyName, null)); + return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId) + .entity(new PdpGroupDeleteResponse()).build(); + + } catch (PfModelException | PfModelRuntimeException e) { + logger.warn("undeploy policy failed", e); + PdpGroupDeleteResponse resp = new PdpGroupDeleteResponse(); + resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); + return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), + requestId).entity(resp).build(); + } } /** @@ -168,10 +187,17 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { @ApiParam(value = "PDP Policy Name", required = true) @PathParam("name") String policyName, @ApiParam(value = "PDP Policy Version", required = true) @PathParam("version") String version) { - Pair<Status, PdpGroupDeleteResponse> pair = - provider.undeploy(new ToscaPolicyIdentifierOptVersion(policyName, version)); - - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); + try { + provider.undeploy(new ToscaPolicyIdentifierOptVersion(policyName, version)); + return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId) + .entity(new PdpGroupDeleteResponse()).build(); + + } catch (PfModelException | PfModelRuntimeException e) { + logger.warn("undeploy policy failed", e); + PdpGroupDeleteResponse resp = new PdpGroupDeleteResponse(); + resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); + return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), + requestId).entity(resp).build(); + } } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeleteProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeleteProvider.java index c64a0efe..6df713d3 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeleteProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeleteProvider.java @@ -21,24 +21,21 @@ package org.onap.policy.pap.main.rest.depundep; import java.util.function.BiFunction; -import javax.ws.rs.core.Response; -import org.apache.commons.lang3.tuple.Pair; +import javax.ws.rs.core.Response.Status; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; -import org.onap.policy.pap.main.PolicyPapRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provider for PAP component to delete PDP groups. */ -public class PdpGroupDeleteProvider extends ProviderBase<PdpGroupDeleteResponse> { +public class PdpGroupDeleteProvider extends ProviderBase { private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeleteProvider.class); @@ -53,11 +50,10 @@ public class PdpGroupDeleteProvider extends ProviderBase<PdpGroupDeleteResponse> * Deletes a PDP group. * * @param groupName name of the PDP group to be deleted - * @return a pair containing the status and the response + * @throws PfModelException if an error occurred */ - public Pair<Response.Status, PdpGroupDeleteResponse> deleteGroup(String groupName) { - - return process(groupName, this::deleteGroup); + public void deleteGroup(String groupName) throws PfModelException { + process(groupName, this::deleteGroup); } /** @@ -65,27 +61,23 @@ public class PdpGroupDeleteProvider extends ProviderBase<PdpGroupDeleteResponse> * * @param data session data * @param groupName name of the PDP group to be deleted + * @throws PfModelException if an error occurred */ - private void deleteGroup(SessionData data, String groupName) { + private void deleteGroup(SessionData data, String groupName) throws PfModelException { try { PdpGroup group = data.getGroup(groupName); if (group == null) { - throw new PolicyPapRuntimeException("group not found"); + throw new PfModelException(Status.NOT_FOUND, "group not found"); } if (group.getPdpGroupState() == PdpState.ACTIVE) { - throw new PolicyPapRuntimeException("group is still " + PdpState.ACTIVE); + throw new PfModelException(Status.BAD_REQUEST, "group is still " + PdpState.ACTIVE); } data.deleteGroupFromDb(group); - } catch (PfModelException e) { - // no need to log the error here, as it will be logged by the invoker - logger.warn("failed to delete group: {}", groupName); - throw new PolicyPapRuntimeException(DB_ERROR_MSG, e); - - } catch (RuntimeException e) { - // no need to log the error here, as it will be logged by the invoker + } catch (PfModelException | RuntimeException e) { + // no need to log the error object here, as it will be logged by the invoker logger.warn("failed to delete group: {}", groupName); throw e; } @@ -95,11 +87,10 @@ public class PdpGroupDeleteProvider extends ProviderBase<PdpGroupDeleteResponse> * Undeploys a policy. * * @param policyIdent identifier of the policy to be undeployed - * @return a pair containing the status and the response + * @throws PfModelException if an error occurred */ - public Pair<Response.Status, PdpGroupDeleteResponse> undeploy(ToscaPolicyIdentifierOptVersion policyIdent) { - - return process(policyIdent, this::undeployPolicy); + public void undeploy(ToscaPolicyIdentifierOptVersion policyIdent) throws PfModelException { + process(policyIdent, this::undeployPolicy); } /** @@ -107,30 +98,19 @@ public class PdpGroupDeleteProvider extends ProviderBase<PdpGroupDeleteResponse> * * @param data session data * @param ident identifier of the policy to be deleted + * @throws PfModelException if an error occurred */ - private void undeployPolicy(SessionData data, ToscaPolicyIdentifierOptVersion ident) { + private void undeployPolicy(SessionData data, ToscaPolicyIdentifierOptVersion ident) throws PfModelException { try { processPolicy(data, ident); - } catch (PfModelException e) { - // no need to log the error here, as it will be logged by the invoker - logger.warn("failed to undeploy policy: {}", ident); - throw new PolicyPapRuntimeException(DB_ERROR_MSG, e); - - } catch (RuntimeException e) { - // no need to log the error here, as it will be logged by the invoker + } catch (PfModelException | RuntimeException e) { + // no need to log the error object here, as it will be logged by the invoker logger.warn("failed to undeploy policy: {}", ident); throw e; } } - @Override - public PdpGroupDeleteResponse makeResponse(String errorMsg) { - PdpGroupDeleteResponse resp = new PdpGroupDeleteResponse(); - resp.setErrorDetails(errorMsg); - return resp; - } - /** * Returns a function that will remove the specified policy from a subgroup. */ diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployControllerV1.java index bdec3562..d3e6c006 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployControllerV1.java @@ -34,16 +34,20 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; -import org.apache.commons.lang3.tuple.Pair; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpDeployPolicies; import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.pap.main.rest.PapRestControllerV1; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Class to provide REST end points for PAP component to deploy a PDP group. */ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { + private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeployControllerV1.class); private final PdpGroupDeployProvider provider = new PdpGroupDeployProvider(); @@ -82,10 +86,18 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { public Response deployGroup(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, @ApiParam(value = "List of PDP Group Configuration", required = true) PdpGroups groups) { - Pair<Status, PdpGroupDeployResponse> pair = provider.createOrUpdateGroups(groups); + try { + provider.createOrUpdateGroups(groups); + return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId) + .entity(new PdpGroupDeployResponse()).build(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); + } catch (PfModelException | PfModelRuntimeException e) { + logger.warn("create groups failed", e); + PdpGroupDeployResponse resp = new PdpGroupDeployResponse(); + resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); + return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), + requestId).entity(resp).build(); + } } /** @@ -124,9 +136,17 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { @ApiParam(value = "PDP Policies; only the name is required", required = true) PdpDeployPolicies policies) { - Pair<Status, PdpGroupDeployResponse> pair = provider.deployPolicies(policies); + try { + provider.deployPolicies(policies); + return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId) + .entity(new PdpGroupDeployResponse()).build(); - return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) - .entity(pair.getRight()).build(); + } catch (PfModelException | PfModelRuntimeException e) { + logger.warn("deploy policies failed", e); + PdpGroupDeployResponse resp = new PdpGroupDeployResponse(); + resp.setErrorDetails(e.getErrorResponse().getErrorMessage()); + return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())), + requestId).entity(resp).build(); + } } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployProvider.java index 5fd1213c..ee66b35c 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployProvider.java @@ -30,16 +30,15 @@ import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Consumer; -import javax.ws.rs.core.Response; -import org.apache.commons.lang3.tuple.Pair; +import javax.ws.rs.core.Response.Status; import org.onap.policy.common.parameters.BeanValidationResult; import org.onap.policy.common.parameters.ObjectValidationResult; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.parameters.ValidationStatus; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpDeployPolicies; -import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpSubGroup; @@ -48,7 +47,6 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; -import org.onap.policy.pap.main.PolicyPapRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,7 +59,7 @@ import org.slf4j.LoggerFactory; * <li>PAP DAO Factory</li> * </ul> */ -public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> { +public class PdpGroupDeployProvider extends ProviderBase { private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeployProvider.class); @@ -76,18 +74,18 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * Creates or updates PDP groups. * * @param groups PDP group configurations to be created or updated - * @return a pair containing the status and the response + * @throws PfModelException if an error occurred */ - public Pair<Response.Status, PdpGroupDeployResponse> createOrUpdateGroups(PdpGroups groups) { + public void createOrUpdateGroups(PdpGroups groups) throws PfModelException { ValidationResult result = groups.validatePapRest(); if (!result.isValid()) { String msg = result.getResult().trim(); logger.warn(msg); - return Pair.of(Response.Status.INTERNAL_SERVER_ERROR, makeResponse(msg)); + throw new PfModelException(Status.BAD_REQUEST, msg); } - return process(groups, this::createOrUpdate); + process(groups, this::createOrUpdate); } /** @@ -95,8 +93,9 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * * @param data session data * @param groups PDP group configurations + * @throws PfModelException if an error occurred */ - private void createOrUpdate(SessionData data, PdpGroups groups) { + private void createOrUpdate(SessionData data, PdpGroups groups) throws PfModelException { BeanValidationResult result = new BeanValidationResult("groups", groups); for (PdpGroup group : groups.getGroups()) { @@ -111,7 +110,7 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> } if (!result.isValid()) { - throw new PolicyPapRuntimeException(result.getResult().trim()); + throw new PfModelException(Status.BAD_REQUEST, result.getResult().trim()); } } @@ -121,8 +120,9 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * @param data session data * @param group the group to be added * @return the validation result + * @throws PfModelException if an error occurred */ - private ValidationResult addGroup(SessionData data, PdpGroup group) { + private ValidationResult addGroup(SessionData data, PdpGroup group) throws PfModelException { BeanValidationResult result = new BeanValidationResult(group.getName(), group); validateGroupOnly(group, result); @@ -176,8 +176,9 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * @param dbgroup the group, as it appears within the DB * @param group the group to be added * @return the validation result + * @throws PfModelException if an error occurred */ - private ValidationResult updateGroup(SessionData data, PdpGroup dbgroup, PdpGroup group) { + private ValidationResult updateGroup(SessionData data, PdpGroup dbgroup, PdpGroup group) throws PfModelException { BeanValidationResult result = new BeanValidationResult(group.getName(), group); if (!ObjectUtils.equals(dbgroup.getProperties(), group.getProperties())) { @@ -242,8 +243,9 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * @param data session data * @param subgrp the subgroup to be added * @return the validation result + * @throws PfModelException if an error occurred */ - private ValidationResult addSubGroup(SessionData data, PdpSubGroup subgrp) { + private ValidationResult addSubGroup(SessionData data, PdpSubGroup subgrp) throws PfModelException { subgrp.setCurrentInstanceCount(0); subgrp.setPdpInstances(Collections.emptyList()); @@ -264,9 +266,10 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * @param container container for additional validation results * @return {@code true} if the subgroup content was changed, {@code false} if there * were no changes + * @throws PfModelException if an error occurred */ private boolean updateSubGroup(SessionData data, PdpGroup dbgroup, PdpSubGroup dbsub, PdpSubGroup subgrp, - BeanValidationResult container) { + BeanValidationResult container) throws PfModelException { // perform additional validations first if (!validateSubGroup(data, dbsub, subgrp, container)) { @@ -301,9 +304,10 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * @param subgrp the subgroup to be validated * @param container container for additional validation results * @return {@code true} if the subgroup is valid, {@code false} otherwise + * @throws PfModelException if an error occurred */ private boolean validateSubGroup(SessionData data, PdpSubGroup dbsub, PdpSubGroup subgrp, - BeanValidationResult container) { + BeanValidationResult container) throws PfModelException { BeanValidationResult result = new BeanValidationResult(subgrp.getPdpType(), subgrp); @@ -346,16 +350,27 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * @param data session data * @param subgrp the subgroup to be validated * @param result the validation result + * @throws PfModelException if an error occurred */ - private ValidationResult validatePolicies(SessionData data, PdpSubGroup subgrp) { + private ValidationResult validatePolicies(SessionData data, PdpSubGroup subgrp) throws PfModelException { BeanValidationResult result = new BeanValidationResult(subgrp.getPdpType(), subgrp); for (ToscaPolicyIdentifier ident : subgrp.getPolicies()) { - ToscaPolicy policy = data.getPolicy(new ToscaPolicyIdentifierOptVersion(ident)); + try { + ToscaPolicy policy = data.getPolicy(new ToscaPolicyIdentifierOptVersion(ident)); + + if (!subgrp.getSupportedPolicyTypes().contains(policy.getTypeIdentifier())) { + result.addResult(new ObjectValidationResult("policy", ident, ValidationStatus.INVALID, + "not a supported policy for the subgroup")); + } + + } catch (PfModelException e) { + if (e.getErrorResponse().getResponseCode() != Status.NOT_FOUND) { + throw e; + } - if (!subgrp.getSupportedPolicyTypes().contains(policy.getTypeIdentifier())) { result.addResult(new ObjectValidationResult("policy", ident, ValidationStatus.INVALID, - "not a supported policy for the subgroup")); + "unknown policy")); } } @@ -366,10 +381,10 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * Deploys or updates PDP policies using the simple API. * * @param policies PDP policies - * @return a pair containing the status and the response + * @throws PfModelException if an error occurred */ - public Pair<Response.Status, PdpGroupDeployResponse> deployPolicies(PdpDeployPolicies policies) { - return process(policies, this::deploySimplePolicies); + public void deployPolicies(PdpDeployPolicies policies) throws PfModelException { + process(policies, this::deploySimplePolicies); } /** @@ -379,20 +394,16 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> * @param data session data * @param extPolicies external PDP policies * @return a list of requests that should be sent to configure the PDPs + * @throws PfModelException if an error occurred */ - private void deploySimplePolicies(SessionData data, PdpDeployPolicies policies) { + private void deploySimplePolicies(SessionData data, PdpDeployPolicies policies) throws PfModelException { for (ToscaPolicyIdentifierOptVersion desiredPolicy : policies.getPolicies()) { try { processPolicy(data, desiredPolicy); - } catch (PfModelException e) { - // no need to log the error here, as it will be logged by the invoker - logger.warn("failed to deploy policy: {}", desiredPolicy); - throw new PolicyPapRuntimeException(DB_ERROR_MSG, e); - - } catch (RuntimeException e) { + } catch (PfModelException | RuntimeException e) { // no need to log the error here, as it will be logged by the invoker logger.warn("failed to deploy policy: {}", desiredPolicy); throw e; @@ -421,8 +432,8 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> } if (subgroup.getPdpInstances().isEmpty()) { - throw new PolicyPapRuntimeException("group " + group.getName() + " subgroup " + subgroup.getPdpType() - + " has no active PDPs"); + throw new PfModelRuntimeException(Status.BAD_REQUEST, "group " + group.getName() + " subgroup " + + subgroup.getPdpType() + " has no active PDPs"); } @@ -431,11 +442,4 @@ public class PdpGroupDeployProvider extends ProviderBase<PdpGroupDeployResponse> return true; }; } - - @Override - public PdpGroupDeployResponse makeResponse(String errorMsg) { - PdpGroupDeployResponse resp = new PdpGroupDeployResponse(); - resp.setErrorDetails(errorMsg); - return resp; - } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/ProviderBase.java b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/ProviderBase.java index 07d04c24..a66b03d2 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/ProviderBase.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/ProviderBase.java @@ -22,14 +22,13 @@ package org.onap.policy.pap.main.rest.depundep; import java.util.Collection; import java.util.Collections; -import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.stream.Collectors; -import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pap.concepts.SimpleResponse; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpStateChange; @@ -41,7 +40,6 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOp import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; -import org.onap.policy.pap.main.PolicyPapRuntimeException; import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,10 +52,8 @@ import org.slf4j.LoggerFactory; * <li>PDP Modify Request Map</li> * <li>PAP DAO Factory</li> * </ul> - * - * @param <R> the response type */ -public abstract class ProviderBase<R extends SimpleResponse> { +public abstract class ProviderBase { private static final String DEPLOY_FAILED = "failed to deploy/undeploy policies"; public static final String DB_ERROR_MSG = "DB error"; @@ -93,9 +89,9 @@ public abstract class ProviderBase<R extends SimpleResponse> { * * @param request PDP policy request * @param processor function that processes the request - * @return a pair containing the status and the response + * @throws PfModelException if an error occurred */ - protected <T> Pair<Response.Status, R> process(T request, BiConsumer<SessionData, T> processor) { + protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException { synchronized (updateLock) { // list of requests to be published to the PDPs @@ -111,49 +107,19 @@ public abstract class ProviderBase<R extends SimpleResponse> { requests = data.getPdpRequests(); - } catch (PfModelException e) { - logger.warn(DEPLOY_FAILED, e); - return Pair.of(Response.Status.INTERNAL_SERVER_ERROR, makeResponse(DB_ERROR_MSG)); - - } catch (PolicyPapRuntimeException e) { + } catch (PfModelException | PfModelRuntimeException e) { logger.warn(DEPLOY_FAILED, e); - return Pair.of(Response.Status.INTERNAL_SERVER_ERROR, makeResponse(e.getMessage())); + throw e; } catch (RuntimeException e) { logger.warn(DEPLOY_FAILED, e); - return Pair.of(Response.Status.INTERNAL_SERVER_ERROR, makeResponse("request failed")); + throw new PfModelException(Status.INTERNAL_SERVER_ERROR, "request failed", e); } // publish the requests requests.forEach(pair -> requestMap.addRequest(pair.getLeft(), pair.getRight())); } - - return Pair.of(Response.Status.OK, makeResponse(null)); - } - - /** - * Makes a response. - * - * @param errorMsg error message, or {@code null} if there was no error - * @return a new response - */ - public abstract R makeResponse(String errorMsg); - - /** - * Finds a Policy having the given name and version. If the specified version is - * {@code null}, then it finds the matching Policy with the latest version. - * - * @param data session data - * @param desiredPolicy the policy desired, with the "name" and optional - * "policyVersion" populated - * @return the matching Policy type - * @throws PolicyPapRuntimeException if there is no matching policy type or a DAO - * error occurs - */ - private ToscaPolicy getPolicy(SessionData data, ToscaPolicyIdentifierOptVersion desiredPolicy) { - - return data.getPolicy(desiredPolicy); } /** @@ -161,8 +127,7 @@ public abstract class ProviderBase<R extends SimpleResponse> { * * @param data session data * @param desiredPolicy request policy - * @throws PolicyPapRuntimeException if an error occurs - * @throws PfModelException if a DAO error occurred + * @throws PfModelException if an error occurred */ protected void processPolicy(SessionData data, ToscaPolicyIdentifierOptVersion desiredPolicy) throws PfModelException { @@ -171,8 +136,8 @@ public abstract class ProviderBase<R extends SimpleResponse> { Collection<PdpGroup> groups = getGroups(data, policy.getTypeIdentifier()); if (groups.isEmpty()) { - throw new PolicyPapRuntimeException("policy not supported by any PDP group: " + desiredPolicy.getName() - + " " + desiredPolicy.getVersion()); + throw new PfModelException(Status.BAD_REQUEST, "policy not supported by any PDP group: " + + desiredPolicy.getName() + " " + desiredPolicy.getVersion()); } BiFunction<PdpGroup, PdpSubGroup, Boolean> updater = makeUpdater(policy); @@ -199,7 +164,7 @@ public abstract class ProviderBase<R extends SimpleResponse> { * @param policyType the policy type of interest * @return the matching PDP group, or {@code null} if no active group supports the * given PDP types - * @throws PfModelException if an error occurs + * @throws PfModelException if an error occurred */ private Collection<PdpGroup> getGroups(SessionData data, ToscaPolicyTypeIdentifier policyType) throws PfModelException { @@ -213,9 +178,9 @@ public abstract class ProviderBase<R extends SimpleResponse> { * @param data session data * @param group the original group, to be updated * @param updater function to update a group + * @throws PfModelRuntimeException if an error occurred */ - private void upgradeGroup(SessionData data, PdpGroup group, - BiFunction<PdpGroup, PdpSubGroup, Boolean> updater) { + private void upgradeGroup(SessionData data, PdpGroup group, BiFunction<PdpGroup, PdpSubGroup, Boolean> updater) { boolean updated = false; @@ -268,8 +233,38 @@ public abstract class ProviderBase<R extends SimpleResponse> { update.setPdpGroup(group.getName()); update.setPdpSubgroup(subgroup.getPdpType()); update.setPolicies(subgroup.getPolicies().stream().map(ToscaPolicyIdentifierOptVersion::new) - .map(data::getPolicy).collect(Collectors.toList())); + .map(ident -> getPolicy(data, ident)).collect(Collectors.toList())); return update; } + + /** + * Gets the specified policy. + * + * @param data session data + * @param ident policy identifier, with an optional version + * @return the policy of interest + * @throws PfModelRuntimeException if an error occurred or the policy was not found + */ + private ToscaPolicy getPolicy(SessionData data, ToscaPolicyIdentifierOptVersion ident) { + try { + return data.getPolicy(ident); + + } catch (PfModelException e) { + throw new PfModelRuntimeException(e.getErrorResponse().getResponseCode(), + e.getErrorResponse().getErrorMessage(), e); + } + } + + @FunctionalInterface + public static interface BiConsumerWithEx<F, S> { + /** + * Performs this operation on the given arguments. + * + * @param firstArg the first input argument + * @param secondArg the second input argument + * @throws PfModelException if an error occurred + */ + void accept(F firstArg, S secondArg) throws PfModelException; + } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/SessionData.java b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/SessionData.java index 5cd2f803..98a5e675 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/depundep/SessionData.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/depundep/SessionData.java @@ -27,6 +27,7 @@ import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; +import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pdp.concepts.PdpGroup; @@ -40,14 +41,14 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter.ToscaPolicyFilterBuilder; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; -import org.onap.policy.pap.main.PolicyPapRuntimeException; /** * Data used during a single REST call when updating PDP policies. */ public class SessionData { /** - * If a version string matches this, then it is just a prefix (i.e., major or major.minor). + * If a version string matches this, then it is just a prefix (i.e., major or + * major.minor). */ private static final Pattern VERSION_PREFIX_PAT = Pattern.compile("[^.]+(?:[.][^.]*)?"); @@ -94,29 +95,24 @@ public class SessionData { * * @param desiredPolicy policy identifier * @return the specified policy - * @throws PolicyPapRuntimeException if an error occurs + * @throws PfModelException if an error occurred */ - public ToscaPolicy getPolicy(ToscaPolicyIdentifierOptVersion desiredPolicy) { + public ToscaPolicy getPolicy(ToscaPolicyIdentifierOptVersion desiredPolicy) throws PfModelException { - ToscaPolicy policy = policyCache.computeIfAbsent(desiredPolicy, key -> { + ToscaPolicy policy = policyCache.get(desiredPolicy); + if (policy == null) { + ToscaPolicyFilterBuilder filterBuilder = ToscaPolicyFilter.builder().name(desiredPolicy.getName()); + setPolicyFilterVersion(filterBuilder, desiredPolicy.getVersion()); - try { - ToscaPolicyFilterBuilder filterBuilder = ToscaPolicyFilter.builder().name(desiredPolicy.getName()); - setPolicyFilterVersion(filterBuilder, desiredPolicy.getVersion()); - - List<ToscaPolicy> lst = dao.getFilteredPolicyList(filterBuilder.build()); - if (lst.isEmpty()) { - throw new PolicyPapRuntimeException("cannot find policy: " + desiredPolicy.getName() + " " - + desiredPolicy.getVersion()); - } - - return lst.get(0); - - } catch (PfModelException e) { - throw new PolicyPapRuntimeException( - "cannot get policy: " + desiredPolicy.getName() + " " + desiredPolicy.getVersion(), e); + List<ToscaPolicy> lst = dao.getFilteredPolicyList(filterBuilder.build()); + if (lst.isEmpty()) { + throw new PfModelException(Status.NOT_FOUND, + "cannot find policy: " + desiredPolicy.getName() + " " + desiredPolicy.getVersion()); } - }); + + policy = lst.get(0); + policyCache.put(desiredPolicy, policy); + } // desired version may have only been a prefix - cache with full identifier, too policyCache.putIfAbsent(new ToscaPolicyIdentifierOptVersion(policy.getIdentifier()), policy); @@ -172,8 +168,8 @@ public class SessionData { } /** - * Adds a state-change to the set of state-change requests, replacing any previous entry for the given - * PDP. + * Adds a state-change to the set of state-change requests, replacing any previous + * entry for the given PDP. * * @param change the state-change to be added */ @@ -243,27 +239,22 @@ public class SessionData { * * @param name name of the group to get * @return the group, or {@code null} if it does not exist - * @throws PolicyPapRuntimeException if an error occurs + * @throws PfModelException if an error occurred */ - public PdpGroup getGroup(String name) { + public PdpGroup getGroup(String name) throws PfModelException { - GroupData data = groupCache.computeIfAbsent(name, key -> { - - try { - List<PdpGroup> lst = dao.getPdpGroups(key); - if (lst.isEmpty()) { - return null; - } - - return new GroupData(lst.get(0)); - - } catch (PfModelException e) { - throw new PolicyPapRuntimeException("cannot get group: " + name, e); + GroupData data = groupCache.get(name); + if (data == null) { + List<PdpGroup> lst = dao.getPdpGroups(name); + if (lst.isEmpty()) { + return null; } - }); + data = new GroupData(lst.get(0)); + groupCache.put(name, data); + } - return (data == null ? null : data.getGroup()); + return data.getGroup(); } /** @@ -271,7 +262,7 @@ public class SessionData { * * @param type desired policy type * @return the active groups supporting the given policy - * @throws PfModelException if an error occurs + * @throws PfModelException if an error occurred */ public List<PdpGroup> getActivePdpGroupsByPolicyType(ToscaPolicyTypeIdentifier type) throws PfModelException { List<GroupData> data = type2groups.get(type); @@ -311,7 +302,7 @@ public class SessionData { /** * Update the DB with the changes. * - * @throws PfModelException if an error occurs + * @throws PfModelException if an error occurred */ public void updateDb() throws PfModelException { // create new groups @@ -333,7 +324,7 @@ public class SessionData { * executed later). * * @param group the group to be deleted - * @throws PfModelException if an error occurs + * @throws PfModelException if an error occurred */ public void deleteGroupFromDb(PdpGroup group) throws PfModelException { dao.deletePdpGroup(group.getName()); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeleteControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeleteControllerV1.java index f7390553..670d1e05 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeleteControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeleteControllerV1.java @@ -29,6 +29,9 @@ import org.junit.Test; import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; import org.onap.policy.pap.main.rest.CommonPapRestServer; +/** + * Note: this tests failure cases; success cases are tested by tests in the "e2e" package. + */ public class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { private static final String GROUP_NOT_FOUND = "group not found"; @@ -50,12 +53,12 @@ public class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { Invocation.Builder invocationBuilder = sendRequest(uri); Response rawresp = invocationBuilder.delete(); PdpGroupDeleteResponse resp = rawresp.readEntity(PdpGroupDeleteResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertEquals(GROUP_NOT_FOUND, resp.getErrorDetails()); rawresp = invocationBuilder.delete(); resp = rawresp.readEntity(PdpGroupDeleteResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertEquals(GROUP_NOT_FOUND, resp.getErrorDetails()); // verify it fails when no authorization info is included @@ -69,12 +72,12 @@ public class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { Invocation.Builder invocationBuilder = sendRequest(uri); Response rawresp = invocationBuilder.delete(); PdpGroupDeleteResponse resp = rawresp.readEntity(PdpGroupDeleteResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertEquals("cannot find policy: my-name null", resp.getErrorDetails()); rawresp = invocationBuilder.delete(); resp = rawresp.readEntity(PdpGroupDeleteResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertEquals("cannot find policy: my-name null", resp.getErrorDetails()); // verify it fails when no authorization info is included @@ -88,12 +91,12 @@ public class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { Invocation.Builder invocationBuilder = sendRequest(uri); Response rawresp = invocationBuilder.delete(); PdpGroupDeleteResponse resp = rawresp.readEntity(PdpGroupDeleteResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertEquals("cannot find policy: my-name 3", resp.getErrorDetails()); rawresp = invocationBuilder.delete(); resp = rawresp.readEntity(PdpGroupDeleteResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertEquals("cannot find policy: my-name 3", resp.getErrorDetails()); // verify it fails when no authorization info is included diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeleteProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeleteProvider.java index 5824b4b0..72765ce6 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeleteProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeleteProvider.java @@ -23,7 +23,6 @@ package org.onap.policy.pap.main.rest.depundep; 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.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; @@ -36,23 +35,19 @@ import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; -import java.util.function.BiConsumer; import java.util.function.BiFunction; import javax.ws.rs.core.Response.Status; -import org.apache.commons.lang3.tuple.Pair; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.PdpUpdate; import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; -import org.onap.policy.pap.main.PolicyPapRuntimeException; public class TestPdpGroupDeleteProvider extends ProviderSuper { private static final String EXPECTED_EXCEPTION = "expected exception"; @@ -111,14 +106,17 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { when(session.getGroup(GROUP1_NAME)).thenReturn(group); - assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PolicyPapRuntimeException.class) + assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class) .hasMessage("group is still ACTIVE"); } @Test public void testDeleteGroup_NotFound() throws Exception { - assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage("group not found"); + assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class) + .hasMessage("group not found").matches(thr -> { + PfModelException ex = (PfModelException) thr; + return (ex.getErrorResponse().getResponseCode() == Status.NOT_FOUND); + }); } @Test @@ -144,15 +142,12 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); doThrow(ex).when(session).deleteGroupFromDb(group); - assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage(ProviderBase.DB_ERROR_MSG); + assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex); } @Test - public void testUndeploy_testDeletePolicy() { - Pair<Status, PdpGroupDeleteResponse> pair = prov.undeploy(optIdent); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + public void testUndeploy_testDeletePolicy() throws Exception { + prov.undeploy(optIdent); } /** @@ -169,9 +164,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group)); when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); - Pair<Status, PdpGroupDeleteResponse> pair = new PdpGroupDeleteProvider().undeploy(optIdent); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + new PdpGroupDeleteProvider().undeploy(optIdent); // should have updated the old group List<PdpGroup> updates = getGroupUpdates(); @@ -199,8 +192,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { prov = spy(prov); doThrow(exc).when(prov).processPolicy(any(), any()); - assertThatThrownBy(() -> prov.undeploy(optIdent)).isInstanceOf(PolicyPapRuntimeException.class) - .hasMessage(PdpGroupDeleteProvider.DB_ERROR_MSG); + assertThatThrownBy(() -> prov.undeploy(optIdent)).isSameAs(exc); } @Test @@ -214,15 +206,6 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testMakeResponse() { - PdpGroupDeleteResponse resp = prov.makeResponse(null); - assertNull(resp.getErrorDetails()); - - resp = prov.makeResponse(EXPECTED_EXCEPTION); - assertEquals(EXPECTED_EXCEPTION, resp.getErrorDetails()); - } - - @Test public void testMakeUpdater() { /* * this group has one policy with a different name, one matching policy, and one @@ -263,10 +246,8 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { private class MyProvider extends PdpGroupDeleteProvider { @Override - protected <T> Pair<Status, PdpGroupDeleteResponse> process(T request, BiConsumer<SessionData, T> processor) { + protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException { processor.accept(session, request); - - return Pair.of(Status.OK, new PdpGroupDeleteResponse()); } @Override diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployControllerV1.java index 6ebad5ff..8c01e029 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployControllerV1.java @@ -37,6 +37,9 @@ import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; import org.onap.policy.pap.main.rest.CommonPapRestServer; +/** + * Note: this tests failure cases; success cases are tested by tests in the "e2e" package. + */ public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { private static final String DEPLOY_GROUP_ENDPOINT = "pdps"; @@ -55,12 +58,12 @@ public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { Invocation.Builder invocationBuilder = sendRequest(DEPLOY_GROUP_ENDPOINT); Response rawresp = invocationBuilder.post(entgrp); PdpGroupDeployResponse resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawresp.getStatus()); assertNotNull(resp.getErrorDetails()); rawresp = invocationBuilder.post(entgrp); resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawresp.getStatus()); assertNotNull(resp.getErrorDetails()); // verify it fails when no authorization info is included @@ -74,12 +77,12 @@ public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { Invocation.Builder invocationBuilder = sendRequest(DEPLOY_POLICIES_ENDPOINT); Response rawresp = invocationBuilder.post(entgrp); PdpGroupDeployResponse resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertNotNull(resp.getErrorDetails()); rawresp = invocationBuilder.post(entgrp); resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertNotNull(resp.getErrorDetails()); // verify it fails when no authorization info is included diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java index 12c2adad..406345c6 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java @@ -20,15 +20,14 @@ package org.onap.policy.pap.main.rest.depundep; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.onap.policy.pap.main.rest.depundep.ProviderBase.DB_ERROR_MSG; import java.util.ArrayList; import java.util.Arrays; @@ -37,14 +36,13 @@ import java.util.List; import java.util.TreeMap; import java.util.stream.Collectors; import javax.ws.rs.core.Response.Status; -import org.apache.commons.lang3.tuple.Pair; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpDeployPolicies; -import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpSubGroup; @@ -56,7 +54,6 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifi public class TestPdpGroupDeployProvider extends ProviderSuper { private static final String EXPECTED_EXCEPTION = "expected exception"; - private static final Object REQUEST_FAILED_MSG = "request failed"; private static final String POLICY2_NAME = "policyB"; private static final String POLICY1_VERSION = "1.2.3"; @@ -92,9 +89,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { @Test public void testCreateOrUpdateGroups() throws Exception { - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json")); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json")); // no groups, so no action should have been taken assertNoGroupAction(); @@ -102,9 +97,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { @Test public void testCreateOrUpdateGroups_InvalidRequest() throws Exception { - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(new PdpGroups()); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertTrue(pair.getRight().getErrorDetails().contains("is null")); + assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class) + .hasMessageContaining("is null"); assertNoGroupAction(); } @@ -114,9 +108,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(groups); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertTrue(pair.getRight().getErrorDetails().contains("pdpGroupState")); + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); assertNoGroupAction(); } @@ -127,7 +120,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup group = groups.getGroups().get(0); group.setPdpGroupState(PdpState.PASSIVE); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); // should not have updated the state assertEquals(PdpState.PASSIVE, group.getPdpGroupState()); @@ -140,9 +133,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(groups); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertTrue(pair.getRight().getErrorDetails().contains("pdpGroupState")); + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); assertNoGroupAction(); } @@ -154,32 +146,31 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // policy won't match supported type groups.getGroups().get(0).getPdpSubgroups().get(0).getSupportedPolicyTypes().get(0).setVersion("99.99.99"); - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(groups); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertTrue(pair.getRight().getErrorDetails().contains("supported policy")); + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("supported policy"); assertNoGroupAction(); } @Test - public void testValidateGroupOnly_NullState() { + public void testValidateGroupOnly_NullState() throws PfModelException { PdpGroups groups = loadPdpGroups("createGroups.json"); groups.getGroups().get(0).setPdpGroupState(null); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); } @Test - public void testValidateGroupOnly_Active() { + public void testValidateGroupOnly_Active() throws PfModelException { PdpGroups groups = loadPdpGroups("createGroups.json"); groups.getGroups().get(0).setPdpGroupState(PdpState.ACTIVE); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); } @Test - public void testValidateGroupOnly_Passive() { + public void testValidateGroupOnly_Passive() throws PfModelException { PdpGroups groups = loadPdpGroups("createGroups.json"); groups.getGroups().get(0).setPdpGroupState(PdpState.PASSIVE); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); } @Test @@ -187,9 +178,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(groups); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertTrue(pair.getRight().getErrorDetails().contains("pdpGroupState")); + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); } @Test @@ -200,7 +190,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup group = new PdpGroup(groups.getGroups().get(0)); when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertNoGroupAction(); } @@ -214,9 +204,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(groups); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertTrue(pair.getRight().getErrorDetails().contains("properties")); + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); assertNoGroupAction(); } @@ -229,7 +218,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { group.setDescription("old description"); when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertGroupUpdateOnly(group); @@ -243,7 +232,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); PdpGroup newgrp = groups.getGroups().get(0); assertEquals(newgrp.toString(), group.toString()); @@ -260,7 +249,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // something different in this subgroup group.getPdpSubgroups().get(0).setDesiredInstanceCount(10); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertEquals(newgrp.toString(), group.toString()); assertGroupUpdateOnly(group); @@ -281,7 +270,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")) .thenReturn(loadPolicies("createGroupNewPolicy.json")); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); Collections.sort(group.getPdpSubgroups().get(0).getPolicies()); @@ -299,7 +288,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup group = new PdpGroup(newgrp); when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertNoGroupAction(); } @@ -313,7 +302,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { group.setDescription(null); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertEquals(newgrp.toString(), group.toString()); assertGroupUpdateOnly(group); @@ -328,7 +317,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { newgrp.setDescription(null); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertEquals(newgrp.toString(), group.toString()); assertGroupUpdateOnly(group); @@ -343,7 +332,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { newgrp.setDescription(group.getDescription() + "-changed"); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertEquals(newgrp.toString(), group.toString()); assertGroupUpdateOnly(group); @@ -355,7 +344,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); PdpGroup newgrp = groups.getGroups().get(0); @@ -368,6 +357,30 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test + public void testAddSubGroup_ValidationPolicyNotFound() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + PfModelException exc = new PfModelException(Status.NOT_FOUND, EXPECTED_EXCEPTION); + when(dao.getFilteredPolicyList(any())).thenThrow(exc); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy"); + } + + @Test + public void testAddSubGroup_ValidationPolicyDaoEx() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); + when(dao.getFilteredPolicyList(any())).thenThrow(exc); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isSameAs(exc); + } + + @Test public void testUpdateSubGroup_Invalid() throws Exception { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); @@ -377,9 +390,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // change properties newgrp.getPdpSubgroups().get(0).setProperties(new TreeMap<>()); - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(groups); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertTrue(pair.getRight().getErrorDetails().contains("properties")); + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); assertNoGroupAction(); } @@ -393,7 +405,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().add(new ToscaPolicyTypeIdentifier("typeX", "9.8.7")); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertEquals(newgrp.toString(), group.toString()); assertGroupUpdateOnly(group); @@ -408,7 +420,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { newgrp.getPdpSubgroups().get(0).setDesiredInstanceCount(20); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); assertEquals(newgrp.toString(), group.toString()); assertGroupUpdateOnly(group); @@ -427,7 +439,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")) .thenReturn(loadPolicies("createGroupNewPolicy.json")); - assertEquals(Status.OK, prov.createOrUpdateGroups(groups).getLeft()); + prov.createOrUpdateGroups(groups); Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); Collections.sort(group.getPdpSubgroups().get(0).getPolicies()); @@ -447,52 +459,52 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { newgrp.setProperties(new TreeMap<>()); - Pair<Status, PdpGroupDeployResponse> pair = prov.createOrUpdateGroups(groups); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertTrue(pair.getRight().getErrorDetails().contains("properties")); + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); assertNoGroupAction(); } @Test - public void testDeployPolicies() { - Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadEmptyRequest()); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + public void testDeployPolicies() throws PfModelException { + prov.deployPolicies(loadEmptyRequest()); } @Test public void testDeploySimplePolicies() throws Exception { - Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + prov.deployPolicies(loadEmptyRequest()); } @Test public void testDeploySimplePolicies_DaoEx() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenThrow(new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION)); + PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); + when(dao.getFilteredPdpGroups(any())).thenThrow(exc); + + assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isSameAs(exc); + } + + @Test + public void testDeploySimplePolicies_DaoPfRtEx() throws Exception { + PfModelRuntimeException exc = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); + when(dao.getFilteredPdpGroups(any())).thenThrow(exc); - Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertEquals(DB_ERROR_MSG, pair.getRight().getErrorDetails()); + assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isSameAs(exc); } @Test public void testDeploySimplePolicies_RuntimeEx() throws Exception { - when(dao.getFilteredPolicyList(any())).thenThrow(new RuntimeException(EXPECTED_EXCEPTION)); + RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION); + when(dao.getFilteredPolicyList(any())).thenThrow(exc); - Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertEquals(REQUEST_FAILED_MSG, pair.getRight().getErrorDetails()); + assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isInstanceOf(PfModelException.class).hasCause(exc); } @Test public void testDeploySimplePolicies_NoGroups() throws Exception { when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("emptyGroups.json")); - Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertEquals("policy not supported by any PDP group: policyA 1.2.3", pair.getRight().getErrorDetails()); + assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isInstanceOf(PfModelException.class) + .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); } @Test @@ -511,9 +523,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); - Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + prov.deployPolicies(loadRequest()); assertGroup(getGroupUpdates(), GROUP1_NAME); @@ -528,10 +538,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // subgroup has no PDPs when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroup_NoPdpsDao.json")); - Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertEquals("group " + GROUP1_NAME + " subgroup " + PDP1_TYPE + " has no active PDPs", - pair.getRight().getErrorDetails()); + assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isInstanceOf(PfModelRuntimeException.class) + .hasMessage("group " + GROUP1_NAME + " subgroup " + PDP1_TYPE + " has no active PDPs"); verify(dao, never()).createPdpGroups(any()); verify(dao, never()).updatePdpGroups(any()); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java index bec93e2d..e8ddd821 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java @@ -22,14 +22,12 @@ package org.onap.policy.pap.main.rest.depundep; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.onap.policy.pap.main.rest.depundep.ProviderBase.DB_ERROR_MSG; import java.util.Arrays; import java.util.Collections; @@ -38,25 +36,22 @@ import java.util.List; import java.util.Queue; import java.util.function.BiFunction; import javax.ws.rs.core.Response.Status; -import org.apache.commons.lang3.tuple.Pair; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PdpDeployPolicies; -import org.onap.policy.models.pap.concepts.SimpleResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.PdpUpdate; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; -import org.onap.policy.pap.main.PolicyPapRuntimeException; import org.powermock.reflect.Whitebox; public class TestProviderBase extends ProviderSuper { private static final String EXPECTED_EXCEPTION = "expected exception"; - private static final Object REQUEST_FAILED_MSG = "request failed"; private static final String POLICY1_NAME = "policyA"; private static final String POLICY1_VERSION = "1.2.3"; @@ -103,9 +98,7 @@ public class TestProviderBase extends ProviderSuper { @Test public void testProcess() throws Exception { - Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + prov.process(loadRequest(), this::handle); assertGroup(getGroupUpdates(), GROUP1_NAME); @@ -114,29 +107,27 @@ public class TestProviderBase extends ProviderSuper { @Test public void testProcess_CreateEx() throws Exception { - when(daofact.create()).thenThrow(new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION)); + PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); + when(daofact.create()).thenThrow(ex); - Pair<Status, MyResponse> pair = prov.process(loadEmptyRequest(), this::handle); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertEquals(DB_ERROR_MSG, pair.getRight().getErrorDetails()); + assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex); } @Test - public void testProcess_PapEx() throws Exception { - when(daofact.create()).thenThrow(new PolicyPapRuntimeException(EXPECTED_EXCEPTION)); + public void testProcess_PfRtEx() throws Exception { + PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); + when(daofact.create()).thenThrow(ex); - Pair<Status, MyResponse> pair = prov.process(loadEmptyRequest(), this::handle); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertEquals(EXPECTED_EXCEPTION, pair.getRight().getErrorDetails()); + assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex); } @Test public void testProcess_RuntimeEx() throws Exception { - when(daofact.create()).thenThrow(new RuntimeException(EXPECTED_EXCEPTION)); + RuntimeException ex = new RuntimeException(EXPECTED_EXCEPTION); + when(daofact.create()).thenThrow(ex); - Pair<Status, MyResponse> pair = prov.process(loadEmptyRequest(), this::handle); - assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); - assertEquals(REQUEST_FAILED_MSG, pair.getRight().getErrorDetails()); + assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isInstanceOf(PfModelException.class) + .hasMessage("request failed").hasCause(ex); } @Test @@ -145,18 +136,18 @@ public class TestProviderBase extends ProviderSuper { SessionData session = new SessionData(dao); ToscaPolicyIdentifierOptVersion ident = new ToscaPolicyIdentifierOptVersion(POLICY1_NAME, POLICY1_VERSION); - assertThatThrownBy(() -> prov.processPolicy(session, ident)).isInstanceOf(PolicyPapRuntimeException.class) + assertThatThrownBy(() -> prov.processPolicy(session, ident)).isInstanceOf(PfModelException.class) .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); } @Test public void testGetPolicy() throws Exception { - Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); + when(dao.getFilteredPolicyList(any())).thenThrow(exc); - verify(dao).getFilteredPolicyList(any()); + assertThatThrownBy(() -> prov.process(loadRequest(), this::handle)).isInstanceOf(PfModelRuntimeException.class) + .hasCause(exc); } @Test @@ -164,9 +155,7 @@ public class TestProviderBase extends ProviderSuper { when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json")) .thenReturn(loadGroups("groups.json")); - Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + prov.process(loadRequest(), this::handle); assertGroup(getGroupUpdates(), GROUP1_NAME); } @@ -190,9 +179,7 @@ public class TestProviderBase extends ProviderSuper { prov.clear(); prov.add(false, true, false, true); - Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + prov.process(loadRequest(), this::handle); assertGroup(getGroupUpdates(), GROUP1_NAME); @@ -242,15 +229,12 @@ public class TestProviderBase extends ProviderSuper { // multiple policies in the request PdpDeployPolicies request = loadFile("updateGroupReqMultiple.json", PdpDeployPolicies.class); - Pair<Status, MyResponse> pair = prov.process(request, (data, deploy) -> { + prov.process(request, (data, deploy) -> { for (ToscaPolicyIdentifierOptVersion policy : deploy.getPolicies()) { handle(data, policy); } }); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); - // verify updates List<PdpGroup> changes = getGroupUpdates(); assertGroup(changes, GROUP1_NAME); @@ -267,9 +251,7 @@ public class TestProviderBase extends ProviderSuper { prov.clear(); prov.add(false); - Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); - assertEquals(Status.OK, pair.getLeft()); - assertNull(pair.getRight().getErrorDetails()); + prov.process(loadRequest(), this::handle); verify(dao, never()).createPdpGroups(any()); verify(dao, never()).updatePdpGroups(any()); @@ -320,18 +302,14 @@ public class TestProviderBase extends ProviderSuper { * * @param data session data * @param request request to be handled + * @throws PfModelException if an error occurred */ - private void handle(SessionData data, ToscaPolicyIdentifierOptVersion request) { - try { - prov.processPolicy(data, request); - - } catch (PfModelException e) { - throw new PolicyPapRuntimeException(e); - } + private void handle(SessionData data, ToscaPolicyIdentifierOptVersion request) throws PfModelException { + prov.processPolicy(data, request); } - private static class MyProvider extends ProviderBase<MyResponse> { + private static class MyProvider extends ProviderBase { /** * Used to determine whether or not to make an update when * {@link #makeUpdater(ToscaPolicy)} is called. The updater function removes an @@ -357,11 +335,6 @@ public class TestProviderBase extends ProviderSuper { } @Override - public MyResponse makeResponse(String errorMsg) { - return new MyResponse(errorMsg); - } - - @Override protected BiFunction<PdpGroup, PdpSubGroup, Boolean> makeUpdater(ToscaPolicy policy) { return (group, subgroup) -> { if (shouldUpdate.remove()) { @@ -376,10 +349,4 @@ public class TestProviderBase extends ProviderSuper { }; } } - - private static class MyResponse extends SimpleResponse { - public MyResponse(String errorMsg) { - setErrorDetails(errorMsg); - } - } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java index e74f9f86..17acd5a2 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java @@ -52,7 +52,6 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; -import org.onap.policy.pap.main.PolicyPapRuntimeException; public class TestSessionData extends ProviderSuper { private static final String GROUP_NAME = "groupA"; @@ -157,7 +156,7 @@ public class TestSessionData extends ProviderSuper { PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, "expected exception"); when(dao.getFilteredPolicyList(any())).thenThrow(ex); - assertThatThrownBy(() -> session.getPolicy(ident)).hasMessage("cannot get policy: myPolicy 1.2.3").hasCause(ex); + assertThatThrownBy(() -> session.getPolicy(ident)).isSameAs(ex); } @Test @@ -370,8 +369,7 @@ public class TestSessionData extends ProviderSuper { PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); when(dao.getPdpGroups(GROUP_NAME)).thenThrow(ex); - assertThatThrownBy(() -> session.getGroup(GROUP_NAME)).isInstanceOf(PolicyPapRuntimeException.class) - .hasCause(ex); + assertThatThrownBy(() -> session.getGroup(GROUP_NAME)).isSameAs(ex); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java index 9ffe1035..463e8d6e 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java @@ -86,7 +86,7 @@ public class PdpGroupDeleteTest extends End2EndBase { // repeat - should fail rawresp = invocationBuilder.delete(); resp = rawresp.readEntity(PdpGroupDeleteResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawresp.getStatus()); assertEquals("group not found", resp.getErrorDetails()); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java index 5279236a..69165d1f 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java @@ -124,7 +124,7 @@ public class PdpGroupDeployTest extends End2EndBase { groups.getGroups().get(0).setProperties(null); rawresp = invocationBuilder.post(entity); resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawresp.getStatus()); assertTrue(resp.getErrorDetails().contains("cannot change properties")); } |