diff options
author | 2019-04-23 11:43:50 -0400 | |
---|---|---|
committer | 2019-04-23 12:41:54 -0400 | |
commit | b13e905e3de91ac7a018f61a95064c170821329e (patch) | |
tree | 2b88ea1e8b876f935fc28aae340ca7ea33686607 /main/src/main | |
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>
Diffstat (limited to 'main/src/main')
7 files changed, 208 insertions, 192 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()); |