aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJim Hahn <jrh3@att.com>2019-07-11 15:26:12 -0400
committerJim Hahn <jrh3@att.com>2019-07-11 16:33:37 -0400
commit75b23a0fa717535fc8308cc92209b3d36f8cf2c9 (patch)
tree11126de5d91913a34c822adb8ec7cb77537fa8be
parent112549df98ef75d071f40632c4f905a83eaacdb0 (diff)
Fix sonar issues in policy-api
Extracted some methods to address cyclomatic complexity. Created super classes to address duplicate code. Did not address code coverage. Change-Id: I2ec07cdad9e671b0e239e2d4ae9395e89b9e4266 Issue-ID: POLICY-1791 Signed-off-by: Jim Hahn <jrh3@att.com>
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java235
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java86
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java96
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java162
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java70
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java70
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java130
-rw-r--r--main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java69
8 files changed, 397 insertions, 521 deletions
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
index 5132bc63..30b004b6 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
@@ -48,7 +48,6 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
import org.apache.commons.lang3.tuple.Pair;
import org.onap.policy.api.main.rest.provider.HealthCheckProvider;
import org.onap.policy.api.main.rest.provider.PolicyProvider;
@@ -58,9 +57,6 @@ import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.report.HealthCheckReport;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
-import org.onap.policy.common.utils.coder.Coder;
-import org.onap.policy.common.utils.coder.CoderException;
-import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.base.PfModelRuntimeException;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
@@ -95,12 +91,10 @@ import org.slf4j.LoggerFactory;
}),
schemes = { SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS },
securityDefinition = @SecurityDefinition(basicAuthDefinitions = { @BasicAuthDefinition(key = "basicAuth") }))
-public class ApiRestController {
+public class ApiRestController extends CommonRestController {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiRestController.class);
- private final Coder coder = new StandardCoder();
-
/**
* Retrieves the healthcheck status of the API component.
*
@@ -145,8 +139,7 @@ public class ApiRestController {
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new HealthCheckProvider().performHealthCheck()).build();
+ return makeOkResponse(requestId, new HealthCheckProvider().performHealthCheck());
}
/**
@@ -193,8 +186,8 @@ public class ApiRestController {
@HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(new StatisticsProvider().fetchCurrentStatistics()).build();
+
+ return makeOkResponse(requestId, new StatisticsProvider().fetchCurrentStatistics());
}
/**
@@ -243,14 +236,11 @@ public class ApiRestController {
try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(null, null);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes", pfme);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -304,14 +294,11 @@ public class ApiRestController {
try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(policyTypeId, null);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/{}", policyTypeId, pfme);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -367,14 +354,11 @@ public class ApiRestController {
try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(policyTypeId, versionId);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/{}/versions/{}", policyTypeId, versionId, pfme);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -428,14 +412,11 @@ public class ApiRestController {
try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchLatestPolicyTypes(policyTypeId);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/{}/versions/latest", policyTypeId, pfme);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -493,14 +474,11 @@ public class ApiRestController {
try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.createPolicyType(body);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.POST);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("POST /policytypes", pfme);
updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.POST);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -558,13 +536,10 @@ public class ApiRestController {
try (PolicyTypeProvider policyTypeProvider = new PolicyTypeProvider()) {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.deletePolicyType(policyTypeId, versionId);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("DELETE /policytypes/{}/versions/{}", policyTypeId, versionId, pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -622,14 +597,11 @@ public class ApiRestController {
ToscaServiceTemplate serviceTemplate =
policyProvider.fetchPolicies(policyTypeId, policyTypeVersion, null, null);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/{}/versions/{}/policies", policyTypeId, policyTypeVersion, pfme);
updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -689,15 +661,12 @@ public class ApiRestController {
ToscaServiceTemplate serviceTemplate = policyProvider
.fetchPolicies(policyTypeId, policyTypeVersion, policyId, null);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("/policytypes/{}/versions/{}/policies/{}", policyTypeId, policyTypeVersion, policyId,
pfme);
updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -759,15 +728,12 @@ public class ApiRestController {
ToscaServiceTemplate serviceTemplate = policyProvider
.fetchPolicies(policyTypeId, policyTypeVersion, policyId, policyVersion);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/{}/versions/{}/policies/{}/versions/{}", policyTypeId,
policyTypeVersion, policyId, policyVersion, pfme);
updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -827,15 +793,12 @@ public class ApiRestController {
ToscaServiceTemplate serviceTemplate =
policyProvider.fetchLatestPolicies(policyTypeId, policyTypeVersion, policyId);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/{}/versions/{}/policies/{}/versions/latest", policyTypeId,
policyTypeVersion, policyId, pfme);
updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -895,15 +858,12 @@ public class ApiRestController {
Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicies = policyProvider
.fetchDeployedPolicies(policyTypeId, policyTypeVersion, policyId);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(deployedPolicies).build();
+ return makeOkResponse(requestId, deployedPolicies);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/{}/versions/{}/policies/{}/versions/deployed", policyTypeId,
policyTypeVersion, policyId, pfme);
updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -970,14 +930,11 @@ public class ApiRestController {
ToscaServiceTemplate serviceTemplate = policyProvider
.createPolicy(policyTypeId, policyTypeVersion, body);
updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("POST /policytypes/{}/versions/{}/policies", policyTypeId, policyTypeVersion, pfme);
updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.POST);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -1039,46 +996,11 @@ public class ApiRestController {
try (PolicyProvider policyProvider = new PolicyProvider()) {
ToscaServiceTemplate serviceTemplate = policyProvider
.deletePolicy(policyTypeId, policyTypeVersion, policyId, policyVersion);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(serviceTemplate).build();
+ return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("DELETE /policytypes/{}/versions/{}/policies/{}/versions/{}", policyTypeId,
policyTypeVersion, policyId, policyVersion, pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
- }
- }
-
- private ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {
- return rb.header("X-MinorVersion", "0").header("X-PatchVersion", "0").header("X-LatestVersion", "1.0.0");
- }
-
- private ResponseBuilder addLoggingHeaders(ResponseBuilder rb, UUID requestId) {
- if (requestId == null) {
- // Generate a random uuid if client does not embed requestId in rest request
- return rb.header("X-ONAP-RequestID", UUID.randomUUID());
- }
- return rb.header("X-ONAP-RequestID", requestId);
- }
-
- /**
- * Converts an object to a JSON string.
- *
- * @param object object to convert
- * @return a JSON string representing the object
- */
- private String toJson(Object object) {
- if (object == null) {
- return null;
- }
-
- try {
- return coder.encode(object);
-
- } catch (CoderException e) {
- LOGGER.warn("cannot convert {} to JSON", object.getClass().getName(), e);
- return null;
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -1097,52 +1019,65 @@ public class ApiRestController {
private void updateApiStatisticsCounter(Target target, Result result, HttpMethod http) {
ApiStatisticsManager.updateTotalApiCallCount();
- if (target == Target.POLICY) {
- if (result == Result.SUCCESS) {
- if (http == HttpMethod.GET) {
- ApiStatisticsManager.updateApiCallSuccessCount();
- ApiStatisticsManager.updateTotalPolicyGetCount();
- ApiStatisticsManager.updatePolicyGetSuccessCount();
- } else if (http == HttpMethod.POST) {
- ApiStatisticsManager.updateApiCallSuccessCount();
- ApiStatisticsManager.updateTotalPolicyPostCount();
- ApiStatisticsManager.updatePolicyPostSuccessCount();
- }
- } else {
- if (http == HttpMethod.GET) {
- ApiStatisticsManager.updateApiCallFailureCount();
- ApiStatisticsManager.updateTotalPolicyGetCount();
- ApiStatisticsManager.updatePolicyGetFailureCount();
- } else {
- ApiStatisticsManager.updateApiCallFailureCount();
- ApiStatisticsManager.updateTotalPolicyPostCount();
- ApiStatisticsManager.updatePolicyPostFailureCount();
- }
+
+ switch (target) {
+ case POLICY:
+ updatePolicyStats(result, http);
+ break;
+ case POLICY_TYPE:
+ updatePolicyTypeStats(result, http);
+ break;
+ default:
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ break;
+ }
+ }
+
+ private void updatePolicyStats(Result result, HttpMethod http) {
+ if (result == Result.SUCCESS) {
+ if (http == HttpMethod.GET) {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ ApiStatisticsManager.updateTotalPolicyGetCount();
+ ApiStatisticsManager.updatePolicyGetSuccessCount();
+ } else if (http == HttpMethod.POST) {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ ApiStatisticsManager.updateTotalPolicyPostCount();
+ ApiStatisticsManager.updatePolicyPostSuccessCount();
}
- } else if (target == Target.POLICY_TYPE) {
- if (result == Result.SUCCESS) {
- if (http == HttpMethod.GET) {
- ApiStatisticsManager.updateApiCallSuccessCount();
- ApiStatisticsManager.updateTotalPolicyTypeGetCount();
- ApiStatisticsManager.updatePolicyTypeGetSuccessCount();
- } else if (http == HttpMethod.POST) {
- ApiStatisticsManager.updateApiCallSuccessCount();
- ApiStatisticsManager.updatePolicyTypePostSuccessCount();
- ApiStatisticsManager.updatePolicyTypePostSuccessCount();
- }
+ } else {
+ if (http == HttpMethod.GET) {
+ ApiStatisticsManager.updateApiCallFailureCount();
+ ApiStatisticsManager.updateTotalPolicyGetCount();
+ ApiStatisticsManager.updatePolicyGetFailureCount();
} else {
- if (http == HttpMethod.GET) {
- ApiStatisticsManager.updateApiCallFailureCount();
- ApiStatisticsManager.updateTotalPolicyTypeGetCount();
- ApiStatisticsManager.updatePolicyTypeGetFailureCount();
- } else {
- ApiStatisticsManager.updateApiCallFailureCount();
- ApiStatisticsManager.updateTotalPolicyTypePostCount();
- ApiStatisticsManager.updatePolicyTypePostFailureCount();
- }
+ ApiStatisticsManager.updateApiCallFailureCount();
+ ApiStatisticsManager.updateTotalPolicyPostCount();
+ ApiStatisticsManager.updatePolicyPostFailureCount();
+ }
+ }
+ }
+
+ private void updatePolicyTypeStats(Result result, HttpMethod http) {
+ if (result == Result.SUCCESS) {
+ if (http == HttpMethod.GET) {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ ApiStatisticsManager.updateTotalPolicyTypeGetCount();
+ ApiStatisticsManager.updatePolicyTypeGetSuccessCount();
+ } else if (http == HttpMethod.POST) {
+ ApiStatisticsManager.updateApiCallSuccessCount();
+ ApiStatisticsManager.updatePolicyTypePostSuccessCount();
+ ApiStatisticsManager.updatePolicyTypePostSuccessCount();
}
} else {
- ApiStatisticsManager.updateApiCallSuccessCount();
+ if (http == HttpMethod.GET) {
+ ApiStatisticsManager.updateApiCallFailureCount();
+ ApiStatisticsManager.updateTotalPolicyTypeGetCount();
+ ApiStatisticsManager.updatePolicyTypeGetFailureCount();
+ } else {
+ ApiStatisticsManager.updateApiCallFailureCount();
+ ApiStatisticsManager.updateTotalPolicyTypePostCount();
+ ApiStatisticsManager.updatePolicyTypePostFailureCount();
+ }
}
}
} \ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java
new file mode 100644
index 00000000..b059490b
--- /dev/null
+++ b/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java
@@ -0,0 +1,86 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy API
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.rest;
+
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import org.onap.policy.common.utils.coder.Coder;
+import org.onap.policy.common.utils.coder.CoderException;
+import org.onap.policy.common.utils.coder.StandardCoder;
+import org.onap.policy.models.errors.concepts.ErrorResponseInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Super class from which REST controllers are derived.
+ */
+public class CommonRestController {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(CommonRestController.class);
+
+ private final Coder coder = new StandardCoder();
+
+
+ protected Response makeOkResponse(UUID requestId, Object respEntity) {
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
+ .entity(respEntity).build();
+ }
+
+ protected <T extends ErrorResponseInfo> Response makeErrorResponse(UUID requestId, T pfme) {
+ return addLoggingHeaders(addVersionControlHeaders(Response.status(pfme.getErrorResponse().getResponseCode())),
+ requestId).entity(pfme.getErrorResponse()).build();
+ }
+
+ protected ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {
+ return rb.header("X-MinorVersion", "0").header("X-PatchVersion", "0").header("X-LatestVersion", "1.0.0");
+ }
+
+ protected ResponseBuilder addLoggingHeaders(ResponseBuilder rb, UUID requestId) {
+ if (requestId == null) {
+ // Generate a random uuid if client does not embed requestId in rest request
+ return rb.header("X-ONAP-RequestID", UUID.randomUUID());
+ }
+ return rb.header("X-ONAP-RequestID", requestId);
+ }
+
+ /**
+ * Converts an object to a JSON string.
+ *
+ * @param object object to convert
+ * @return a JSON string representing the object
+ */
+ protected String toJson(Object object) {
+ if (object == null) {
+ return null;
+ }
+
+ try {
+ return coder.encode(object);
+
+ } catch (CoderException e) {
+ LOGGER.warn("cannot convert {} to JSON", object.getClass().getName(), e);
+ return null;
+ }
+ }
+}
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java
index 05bb92f8..54155a6f 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java
@@ -42,15 +42,11 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
import org.onap.policy.api.main.rest.provider.LegacyGuardPolicyProvider;
import org.onap.policy.api.main.rest.provider.LegacyOperationalPolicyProvider;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
-import org.onap.policy.common.utils.coder.Coder;
-import org.onap.policy.common.utils.coder.CoderException;
-import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.base.PfModelRuntimeException;
import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
@@ -68,12 +64,10 @@ import org.slf4j.LoggerFactory;
@Api(value = "Legacy Policy Design API")
@Produces("application/json")
@Consumes("application/json")
-public class LegacyApiRestController {
+public class LegacyApiRestController extends CommonRestController {
private static final Logger LOGGER = LoggerFactory.getLogger(LegacyApiRestController.class);
- private final Coder coder = new StandardCoder();
-
/**
* Retrieves the latest version of a particular guard policy.
*
@@ -123,14 +117,11 @@ public class LegacyApiRestController {
try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) {
Map<String, LegacyGuardPolicyOutput> policies = guardPolicyProvider.fetchGuardPolicy(policyId, null);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(policies).build();
+ return makeOkResponse(requestId, policies);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/{}"
+ "/versions/latest", policyId, pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -186,14 +177,11 @@ public class LegacyApiRestController {
try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) {
Map<String, LegacyGuardPolicyOutput> policies = guardPolicyProvider
.fetchGuardPolicy(policyId, policyVersion);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(policies).build();
+ return makeOkResponse(requestId, policies);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/{}/versions/{}",
policyId, policyVersion, pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -251,13 +239,10 @@ public class LegacyApiRestController {
try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) {
Map<String, LegacyGuardPolicyOutput> policy = guardPolicyProvider.createGuardPolicy(body);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(policy).build();
+ return makeOkResponse(requestId, policy);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("POST /policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies", pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -314,14 +299,11 @@ public class LegacyApiRestController {
try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) {
Map<String, LegacyGuardPolicyOutput> policies = guardPolicyProvider
.deleteGuardPolicy(policyId, policyVersion);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(policies).build();
+ return makeOkResponse(requestId, policies);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("DELETE /policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/{}/versions/{}",
policyId, policyVersion, pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -374,14 +356,11 @@ public class LegacyApiRestController {
try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) {
LegacyOperationalPolicy policy = operationalPolicyProvider.fetchOperationalPolicy(policyId, null);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(policy).build();
+ return makeOkResponse(requestId, policy);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/{}"
+ "/versions/latest", policyId, pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -437,14 +416,11 @@ public class LegacyApiRestController {
try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) {
LegacyOperationalPolicy policy = operationalPolicyProvider.fetchOperationalPolicy(policyId, policyVersion);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(policy).build();
+ return makeOkResponse(requestId, policy);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("GET /policytypes/onap.policies.controlloop.Operational/versions/1.0.0/"
+ "policies/{}/versions/{}", policyId, policyVersion, pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -502,13 +478,10 @@ public class LegacyApiRestController {
try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) {
LegacyOperationalPolicy policy = operationalPolicyProvider.createOperationalPolicy(body);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(policy).build();
+ return makeOkResponse(requestId, policy);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("POST /policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies", pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
+ return makeErrorResponse(requestId, pfme);
}
}
@@ -566,46 +539,11 @@ public class LegacyApiRestController {
try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) {
LegacyOperationalPolicy policy = operationalPolicyProvider
.deleteOperationalPolicy(policyId, policyVersion);
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(policy).build();
+ return makeOkResponse(requestId, policy);
} catch (PfModelException | PfModelRuntimeException pfme) {
LOGGER.error("DELETE /policytypes/onap.policies.controlloop.Operational/versions/1.0.0/"
+ "policies/{}/versions/{}", policyId, policyVersion, pfme);
- return addLoggingHeaders(addVersionControlHeaders(
- Response.status(pfme.getErrorResponse().getResponseCode())), requestId)
- .entity(pfme.getErrorResponse()).build();
- }
- }
-
- private ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {
- return rb.header("X-MinorVersion", "0").header("X-PatchVersion", "0").header("X-LatestVersion", "1.0.0");
- }
-
- private ResponseBuilder addLoggingHeaders(ResponseBuilder rb, UUID requestId) {
- if (requestId == null) {
- // Generate a random uuid if client does not embed requestId in rest request
- return rb.header("X-ONAP-RequestID", UUID.randomUUID());
- }
- return rb.header("X-ONAP-RequestID", requestId);
- }
-
- /**
- * Converts an object to a JSON string.
- *
- * @param object object to convert
- * @return a JSON string representing the object
- */
- private String toJson(Object object) {
- if (object == null) {
- return null;
- }
-
- try {
- return coder.encode(object);
-
- } catch (CoderException e) {
- LOGGER.warn("cannot convert {} to JSON", object.getClass().getName(), e);
- return null;
+ return makeErrorResponse(requestId, pfme);
}
}
} \ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java
new file mode 100644
index 00000000..6e9b52b9
--- /dev/null
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java
@@ -0,0 +1,162 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy API
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.rest.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import javax.ws.rs.core.Response;
+import org.onap.policy.api.main.parameters.ApiParameterGroup;
+import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.pdp.concepts.PdpGroup;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+
+/**
+ * Super class for providers that use a model provider.
+ */
+public class CommonModelProvider implements AutoCloseable {
+
+ protected final PolicyModelsProvider modelsProvider;
+
+ /**
+ * Constructs the object, populating {@link #modelsProvider}.
+ *
+ * @throws PfModelException if an error occurs
+ */
+ public CommonModelProvider() throws PfModelException {
+
+ ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
+ PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
+ modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+ }
+
+ /**
+ * Closes the connection to database.
+ *
+ * @throws PfModelException the PfModel parsing exception
+ */
+ @Override
+ public void close() throws PfModelException {
+
+ modelsProvider.close();
+ }
+
+ /**
+ * Checks if service template contains any policy.
+ *
+ * @param serviceTemplate the service template to check against
+ *
+ * @return boolean whether service template contains any policy
+ */
+ protected boolean hasPolicy(ToscaServiceTemplate serviceTemplate) {
+
+ return hasData(serviceTemplate.getToscaTopologyTemplate().getPolicies());
+ }
+
+ /**
+ * Checks if service template contains any policy type.
+ *
+ * @param serviceTemplate the service template to check against
+ *
+ * @return boolean whether service template contains any policy type
+ */
+ protected boolean hasPolicyType(ToscaServiceTemplate serviceTemplate) {
+
+ return hasData(serviceTemplate.getPolicyTypes());
+ }
+
+ /**
+ * Checks if the first element of a list contains data.
+ *
+ * @param list list to be examined
+ * @return {@code true} if the list contains data, {@code false} otherwise
+ */
+ protected <T> boolean hasData(List<Map<String, T>> list) {
+
+ return (list != null && !list.isEmpty() && !list.get(0).isEmpty());
+ }
+
+ /**
+ * Validates that some text represents a number.
+ *
+ * @param text text to be validated
+ * @param errorMsg error message included in the exception, if the text is not a valid
+ * number
+ * @throws PfModelException if the text is not a valid number
+ */
+ protected void validNumber(String text, String errorMsg) throws PfModelException {
+ try {
+ Integer.parseInt(text);
+
+ } catch (NumberFormatException exc) {
+ throw new PfModelException(Response.Status.BAD_REQUEST, errorMsg, exc);
+ }
+ }
+
+ /**
+ * Constructs returned message for policy delete rule violation.
+ *
+ * @param policyId the ID of policy
+ * @param policyVersion the version of policy
+ * @param pdpGroups the list of pdp groups
+ *
+ * @return the constructed message
+ */
+ protected String constructDeletePolicyViolationMessage(String policyId, String policyVersion,
+ List<PdpGroup> pdpGroups) {
+
+ List<String> pdpGroupNameVersionList = new ArrayList<>(pdpGroups.size());
+ for (PdpGroup pdpGroup : pdpGroups) {
+ pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion());
+ }
+ String deployedPdpGroups = String.join(",", pdpGroupNameVersionList);
+ return "policy with ID " + policyId + ":" + policyVersion
+ + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups;
+ }
+
+ /**
+ * Constructs returned message for policy type delete rule violation.
+ *
+ * @param policyTypeId the ID of policy type
+ * @param policyTypeVersion the version of policy type
+ * @param policies the list of policies that parameterizes specified policy type
+ *
+ * @return the constructed message
+ */
+ protected String constructDeletePolicyTypeViolationMessage(String policyTypeId, String policyTypeVersion,
+ List<ToscaPolicy> policies) {
+
+ List<String> policyNameVersionList = new ArrayList<>(policies.size());
+ for (ToscaPolicy policy : policies) {
+ policyNameVersionList.add(policy.getName() + ":" + policy.getVersion());
+ }
+ String parameterizedPolicies = String.join(",", policyNameVersionList);
+ return "policy type with ID " + policyTypeId + ":" + policyTypeVersion
+ + " cannot be deleted as it is parameterized by policies " + parameterizedPolicies;
+ }
+}
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java
index 44cc046f..2f450866 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java
@@ -26,14 +26,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.common.parameters.ParameterService;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.pdp.concepts.PdpGroup;
import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
-import org.onap.policy.models.provider.PolicyModelsProvider;
-import org.onap.policy.models.provider.PolicyModelsProviderFactory;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
@@ -43,18 +38,16 @@ import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
*
* @author Chenfei Gao (cgao@research.att.com)
*/
-public class LegacyGuardPolicyProvider implements AutoCloseable {
+public class LegacyGuardPolicyProvider extends CommonModelProvider {
+
+ private static final String INVALID_POLICY_VERSION = "legacy policy version is not an integer";
- private PolicyModelsProvider modelsProvider;
/**
* Default constructor.
*/
public LegacyGuardPolicyProvider() throws PfModelException {
-
- ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
- PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
- modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+ super();
}
/**
@@ -69,7 +62,7 @@ public class LegacyGuardPolicyProvider implements AutoCloseable {
throws PfModelException {
if (policyVersion != null) {
- validateLegacyGuardPolicyVersion(policyVersion);
+ validNumber(policyVersion, INVALID_POLICY_VERSION);
}
return modelsProvider.getGuardPolicy(policyId, policyVersion);
}
@@ -98,7 +91,7 @@ public class LegacyGuardPolicyProvider implements AutoCloseable {
public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(String policyId, String policyVersion)
throws PfModelException {
- validateLegacyGuardPolicyVersion(policyVersion);
+ validNumber(policyVersion, INVALID_POLICY_VERSION);
validateDeleteEligibility(policyId, policyVersion);
return modelsProvider.deleteGuardPolicy(policyId, policyVersion);
@@ -122,56 +115,7 @@ public class LegacyGuardPolicyProvider implements AutoCloseable {
if (!pdpGroups.isEmpty()) {
throw new PfModelException(Response.Status.CONFLICT,
- constructDeleteRuleViolationMessage(policyId, policyVersion, pdpGroups));
+ constructDeletePolicyViolationMessage(policyId, policyVersion, pdpGroups));
}
}
-
- /**
- * Validates whether the legacy guard policy version is an integer.
- *
- * @param policyVersion the version of policy
- *
- * @throws PfModelException the PfModel parsing exception
- */
- private void validateLegacyGuardPolicyVersion(String policyVersion) throws PfModelException {
-
- try {
- Integer.valueOf(policyVersion);
- } catch (NumberFormatException exc) {
- throw new PfModelException(Response.Status.BAD_REQUEST,
- "legacy policy version is not an integer", exc);
- }
- }
-
- /**
- * Constructs returned message for policy delete rule violation.
- *
- * @param policyId the ID of policy
- * @param policyVersion the version of policy
- * @param pdpGroups the list of pdp groups
- *
- * @return the constructed message
- */
- private String constructDeleteRuleViolationMessage(
- String policyId, String policyVersion, List<PdpGroup> pdpGroups) {
-
- List<String> pdpGroupNameVersionList = new ArrayList<>();
- for (PdpGroup pdpGroup : pdpGroups) {
- pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion());
- }
- String deployedPdpGroups = String.join(",", pdpGroupNameVersionList);
- return "policy with ID " + policyId + ":" + policyVersion
- + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups;
- }
-
- /**
- * Closes the connection to database.
- *
- * @throws PfModelException the PfModel parsing exception
- */
- @Override
- public void close() throws PfModelException {
-
- modelsProvider.close();
- }
} \ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java
index a931f593..965ecdce 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java
@@ -25,14 +25,9 @@ package org.onap.policy.api.main.rest.provider;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Response;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.common.parameters.ParameterService;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.pdp.concepts.PdpGroup;
import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
-import org.onap.policy.models.provider.PolicyModelsProvider;
-import org.onap.policy.models.provider.PolicyModelsProviderFactory;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
@@ -41,18 +36,16 @@ import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
*
* @author Chenfei Gao (cgao@research.att.com)
*/
-public class LegacyOperationalPolicyProvider implements AutoCloseable {
+public class LegacyOperationalPolicyProvider extends CommonModelProvider {
+
+ private static final String INVALID_POLICY_VERSION = "legacy policy version is not an integer";
- private PolicyModelsProvider modelsProvider;
/**
* Default constructor.
*/
public LegacyOperationalPolicyProvider() throws PfModelException {
-
- ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
- PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
- modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+ super();
}
/**
@@ -67,7 +60,7 @@ public class LegacyOperationalPolicyProvider implements AutoCloseable {
throws PfModelException {
if (policyVersion != null) {
- validateLegacyOperationalPolicyVersion(policyVersion);
+ validNumber(policyVersion, INVALID_POLICY_VERSION);
}
return modelsProvider.getOperationalPolicy(policyId, policyVersion);
}
@@ -95,7 +88,7 @@ public class LegacyOperationalPolicyProvider implements AutoCloseable {
public LegacyOperationalPolicy deleteOperationalPolicy(String policyId, String policyVersion)
throws PfModelException {
- validateLegacyOperationalPolicyVersion(policyVersion);
+ validNumber(policyVersion, INVALID_POLICY_VERSION);
validateDeleteEligibility(policyId, policyVersion);
return modelsProvider.deleteOperationalPolicy(policyId, policyVersion);
@@ -119,56 +112,7 @@ public class LegacyOperationalPolicyProvider implements AutoCloseable {
if (!pdpGroups.isEmpty()) {
throw new PfModelException(Response.Status.CONFLICT,
- constructDeleteRuleViolationMessage(policyId, policyVersion, pdpGroups));
+ constructDeletePolicyViolationMessage(policyId, policyVersion, pdpGroups));
}
}
-
- /**
- * Validates whether the legacy operational policy version is an integer.
- *
- * @param policyVersion the version of policy
- *
- * @throws PfModelException the PfModel parsing exception
- */
- private void validateLegacyOperationalPolicyVersion(String policyVersion) throws PfModelException {
-
- try {
- Integer.valueOf(policyVersion);
- } catch (NumberFormatException exc) {
- throw new PfModelException(Response.Status.BAD_REQUEST,
- "legacy policy version is not an integer", exc);
- }
- }
-
- /**
- * Constructs returned message for policy delete rule violation.
- *
- * @param policyId the ID of policy
- * @param policyVersion the version of policy
- * @param pdpGroups the list of pdp groups
- *
- * @return the constructed message
- */
- private String constructDeleteRuleViolationMessage(
- String policyId, String policyVersion, List<PdpGroup> pdpGroups) {
-
- List<String> pdpGroupNameVersionList = new ArrayList<>();
- for (PdpGroup pdpGroup : pdpGroups) {
- pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion());
- }
- String deployedPdpGroups = String.join(",", pdpGroupNameVersionList);
- return "policy with ID " + policyId + ":" + policyVersion
- + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups;
- }
-
- /**
- * Closes the connection to database.
- *
- * @throws PfModelException the PfModel parsing exception
- */
- @Override
- public void close() throws PfModelException {
-
- modelsProvider.close();
- }
} \ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
index 102f6f88..a4440daf 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
@@ -28,16 +28,11 @@ import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.tuple.Pair;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.common.parameters.ParameterService;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.pdp.concepts.PdpGroup;
import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
import org.onap.policy.models.pdp.concepts.PdpSubGroup;
import org.onap.policy.models.pdp.enums.PdpState;
-import org.onap.policy.models.provider.PolicyModelsProvider;
-import org.onap.policy.models.provider.PolicyModelsProviderFactory;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
@@ -49,18 +44,13 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
*
* @author Chenfei Gao (cgao@research.att.com)
*/
-public class PolicyProvider implements AutoCloseable {
-
- private PolicyModelsProvider modelsProvider;
+public class PolicyProvider extends CommonModelProvider {
/**
* Default constructor.
*/
public PolicyProvider() throws PfModelException {
-
- ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
- PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
- modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+ super();
}
/**
@@ -270,32 +260,11 @@ public class PolicyProvider implements AutoCloseable {
if (!pdpGroups.isEmpty()) {
throw new PfModelException(Response.Status.CONFLICT,
- constructDeleteRuleViolationMessage(policyId, policyVersion, pdpGroups));
+ constructDeletePolicyViolationMessage(policyId, policyVersion, pdpGroups));
}
}
/**
- * Constructs returned message for policy delete rule violation.
- *
- * @param policyId the ID of policy
- * @param policyVersion the version of policy
- * @param pdpGroups the list of pdp groups
- *
- * @return the constructed message
- */
- private String constructDeleteRuleViolationMessage(
- String policyId, String policyVersion, List<PdpGroup> pdpGroups) {
-
- List<String> pdpGroupNameVersionList = new ArrayList<>();
- for (PdpGroup pdpGroup : pdpGroups) {
- pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion());
- }
- String deployedPdpGroups = String.join(",", pdpGroupNameVersionList);
- return "policy with ID " + policyId + ":" + policyVersion
- + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups;
- }
-
- /**
* Constructs the map of deployed pdp groups and deployed policies.
*
* @param pdpGroups the list of pdp groups that contain the specified policy
@@ -310,21 +279,8 @@ public class PolicyProvider implements AutoCloseable {
Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicyMap = new HashMap<>();
for (PdpGroup pdpGroup : pdpGroups) {
- List<ToscaPolicyIdentifier> policyIdentifiers = new ArrayList<>();
- for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
- for (ToscaPolicyIdentifier policyIdentifier : pdpSubGroup.getPolicies()) {
- if (policyId.equalsIgnoreCase(policyIdentifier.getName())) {
- policyIdentifiers.add(policyIdentifier);
- }
- }
- }
- List<ToscaPolicy> deployedPolicies = new ArrayList<>();
- if (!policyIdentifiers.isEmpty()) {
- for (ToscaPolicyIdentifier policyIdentifier : policyIdentifiers) {
- deployedPolicies.addAll(
- modelsProvider.getPolicyList(policyIdentifier.getName(), policyIdentifier.getVersion()));
- }
- }
+ List<ToscaPolicyIdentifier> policyIdentifiers = extractPolicyIdentifiers(policyId, pdpGroup);
+ List<ToscaPolicy> deployedPolicies = getDeployedPolicies(policyIdentifiers);
if (!deployedPolicies.isEmpty()) {
deployedPolicyMap.put(Pair.of(pdpGroup.getName(), pdpGroup.getVersion()), deployedPolicies);
}
@@ -332,6 +288,31 @@ public class PolicyProvider implements AutoCloseable {
return deployedPolicyMap;
}
+ private List<ToscaPolicyIdentifier> extractPolicyIdentifiers(String policyId, PdpGroup pdpGroup) {
+ List<ToscaPolicyIdentifier> policyIdentifiers = new ArrayList<>();
+ for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
+ for (ToscaPolicyIdentifier policyIdentifier : pdpSubGroup.getPolicies()) {
+ if (policyId.equalsIgnoreCase(policyIdentifier.getName())) {
+ policyIdentifiers.add(policyIdentifier);
+ }
+ }
+ }
+ return policyIdentifiers;
+ }
+
+ private List<ToscaPolicy> getDeployedPolicies(List<ToscaPolicyIdentifier> policyIdentifiers)
+ throws PfModelException {
+
+ List<ToscaPolicy> deployedPolicies = new ArrayList<>();
+ if (!policyIdentifiers.isEmpty()) {
+ for (ToscaPolicyIdentifier policyIdentifier : policyIdentifiers) {
+ deployedPolicies.addAll(
+ modelsProvider.getPolicyList(policyIdentifier.getName(), policyIdentifier.getVersion()));
+ }
+ }
+ return deployedPolicies;
+ }
+
/**
* Constructs returned message for not found resource.
*
@@ -365,55 +346,4 @@ public class PolicyProvider implements AutoCloseable {
return "could not find policy with ID " + policyId + " and type "
+ policyTypeId + ":" + policyTypeVersion + " deployed in any pdp group";
}
-
- /**
- * Checks if service template contains any policy.
- *
- * @param serviceTemplate the service template to check against
- *
- * @return boolean whether service template contains any policy
- */
- private boolean hasPolicy(ToscaServiceTemplate serviceTemplate) {
-
- if (serviceTemplate.getToscaTopologyTemplate().getPolicies() == null) {
- return false;
- } else if (serviceTemplate.getToscaTopologyTemplate().getPolicies().isEmpty()) {
- return false;
- } else if (serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()) {
- return false;
- } else {
- return true;
- }
- }
-
- /**
- * Checks if service template contains any policy type.
- *
- * @param serviceTemplate the service template to check against
- *
- * @return boolean whether service template contains any policy type
- */
- private boolean hasPolicyType(ToscaServiceTemplate serviceTemplate) {
-
- if (serviceTemplate.getPolicyTypes() == null) {
- return false;
- } else if (serviceTemplate.getPolicyTypes().isEmpty()) {
- return false;
- } else if (serviceTemplate.getPolicyTypes().get(0).isEmpty()) {
- return false;
- } else {
- return true;
- }
- }
-
- /**
- * Closes the connection to database.
- *
- * @throws PfModelException the PfModel parsing exception
- */
- @Override
- public void close() throws PfModelException {
-
- modelsProvider.close();
- }
}
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java
index 24b8b1bd..57524518 100644
--- a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java
+++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java
@@ -22,15 +22,9 @@
package org.onap.policy.api.main.rest.provider;
-import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Response;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.common.parameters.ParameterService;
import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.provider.PolicyModelsProvider;
-import org.onap.policy.models.provider.PolicyModelsProviderFactory;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter;
@@ -41,18 +35,13 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
*
* @author Chenfei Gao (cgao@research.att.com)
*/
-public class PolicyTypeProvider implements AutoCloseable {
-
- private PolicyModelsProvider modelsProvider;
+public class PolicyTypeProvider extends CommonModelProvider {
/**
* Default constructor.
*/
public PolicyTypeProvider() throws PfModelException {
-
- ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
- PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
- modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
+ super();
}
/**
@@ -156,32 +145,11 @@ public class PolicyTypeProvider implements AutoCloseable {
List<ToscaPolicy> policies = modelsProvider.getFilteredPolicyList(policyFilter);
if (!policies.isEmpty()) {
throw new PfModelException(Response.Status.CONFLICT,
- constructDeleteRuleViolationMessage(policyTypeId, policyTypeVersion, policies));
+ constructDeletePolicyTypeViolationMessage(policyTypeId, policyTypeVersion, policies));
}
}
/**
- * Constructs returned message for policy type delete rule violation.
- *
- * @param policyTypeId the ID of policy type
- * @param policyTypeVersion the version of policy type
- * @param policies the list of policies that parameterizes specified policy type
- *
- * @return the constructed message
- */
- private String constructDeleteRuleViolationMessage(
- String policyTypeId, String policyTypeVersion, List<ToscaPolicy> policies) {
-
- List<String> policyNameVersionList = new ArrayList<>();
- for (ToscaPolicy policy : policies) {
- policyNameVersionList.add(policy.getName() + ":" + policy.getVersion());
- }
- String parameterizedPolicies = String.join(",", policyNameVersionList);
- return "policy type with ID " + policyTypeId + ":" + policyTypeVersion
- + " cannot be deleted as it is parameterized by policies " + parameterizedPolicies;
- }
-
- /**
* Constructs returned message for not found resource.
*
* @param policyTypeId the ID of policy type
@@ -193,35 +161,4 @@ public class PolicyTypeProvider implements AutoCloseable {
return "policy type with ID " + policyTypeId + ":" + policyTypeVersion + " does not exist";
}
-
- /**
- * Checks if service template contains any policy type.
- *
- * @param serviceTemplate the service template to check against
- *
- * @return boolean whether service template contains any policy type
- */
- private boolean hasPolicyType(ToscaServiceTemplate serviceTemplate) {
-
- if (serviceTemplate.getPolicyTypes() == null) {
- return false;
- } else if (serviceTemplate.getPolicyTypes().isEmpty()) {
- return false;
- } else if (serviceTemplate.getPolicyTypes().get(0).isEmpty()) {
- return false;
- } else {
- return true;
- }
- }
-
- /**
- * Closes the connection to database.
- *
- * @throws PfModelException the PfModel parsing exception
- */
- @Override
- public void close() throws PfModelException {
-
- modelsProvider.close();
- }
}