aboutsummaryrefslogtreecommitdiffstats
path: root/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api
diff options
context:
space:
mode:
Diffstat (limited to 'ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api')
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java591
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java80
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java39
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java188
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java159
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java95
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java105
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java97
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java106
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java115
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java111
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java136
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java102
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java156
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java92
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java35
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java294
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java100
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java258
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java107
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java303
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java180
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java273
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java160
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java64
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java123
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java900
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java398
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java186
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java261
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java171
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java72
32 files changed, 6057 insertions, 0 deletions
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java
new file mode 100644
index 000000000..47afcda67
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java
@@ -0,0 +1,591 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.controller;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.Collection;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.policy.api.ConfigRequestParameters;
+import org.openecomp.policy.api.DecisionRequestParameters;
+import org.openecomp.policy.api.DecisionResponse;
+import org.openecomp.policy.api.DeletePolicyParameters;
+import org.openecomp.policy.api.DictionaryParameters;
+import org.openecomp.policy.api.DictionaryResponse;
+import org.openecomp.policy.api.EventRequestParameters;
+import org.openecomp.policy.api.MetricsResponse;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.api.PolicyResponse;
+import org.openecomp.policy.api.PushPolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.XACMLPdpServlet;
+import org.openecomp.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest;
+import org.openecomp.policy.pdp.rest.api.models.ConfigNameRequest;
+import org.openecomp.policy.pdp.rest.api.models.ConfigPolicyAPIRequest;
+import org.openecomp.policy.pdp.rest.api.models.PolicyConfig;
+import org.openecomp.policy.pdp.rest.api.services.CreateUpdateConfigPolicyService;
+import org.openecomp.policy.pdp.rest.api.services.CreateUpdateDictionaryService;
+import org.openecomp.policy.pdp.rest.api.services.CreateUpdateFirewallPolicyService;
+import org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyService;
+import org.openecomp.policy.pdp.rest.api.services.DeletePolicyService;
+import org.openecomp.policy.pdp.rest.api.services.GetConfigService;
+import org.openecomp.policy.pdp.rest.api.services.GetDecisionService;
+import org.openecomp.policy.pdp.rest.api.services.GetDictionaryService;
+import org.openecomp.policy.pdp.rest.api.services.GetMetricsService;
+import org.openecomp.policy.pdp.rest.api.services.ListConfigService;
+import org.openecomp.policy.pdp.rest.api.services.PolicyEngineImportService;
+import org.openecomp.policy.pdp.rest.api.services.PushPolicyService;
+import org.openecomp.policy.pdp.rest.api.services.SendEventService;
+import org.openecomp.policy.pdp.rest.config.PDPApiAuth;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import springfox.documentation.annotations.ApiIgnore;
+
+@RestController
+@Api(value = "Policy Engine Services")
+@RequestMapping("/")
+public class PolicyEngineServices {
+ private static Logger LOGGER = FlexLogger
+ .getLogger(PolicyEngineServices.class.getName());
+ private final AtomicLong configCounter = new AtomicLong();
+ private final AtomicLong configNameCounter = new AtomicLong();
+ private final AtomicLong eventCounter = new AtomicLong();
+ private final AtomicLong decisionCounter = new AtomicLong();
+ private final AtomicLong pushCounter = new AtomicLong();
+ private final AtomicLong deleteCounter = new AtomicLong();
+ private final AtomicLong createPolicyCounter = new AtomicLong();
+ private final AtomicLong updatePolicyCounter = new AtomicLong();
+ private final AtomicLong createDictionaryCounter = new AtomicLong();
+ private final AtomicLong updateDictionaryCounter = new AtomicLong();
+ private final AtomicLong getDictionaryCounter = new AtomicLong();
+ private final AtomicLong policyEngineImportCounter = new AtomicLong();
+ private final AtomicLong deprecatedCounter = new AtomicLong();
+ private final AtomicLong metricCounter = new AtomicLong();
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP)")
+ @RequestMapping(value = "/getConfig", method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity<Collection<PolicyConfig>> getConfig(
+ @RequestBody ConfigRequestParameters configRequestParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ Collection<PolicyConfig> policyConfig = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getConfig")) {
+ GetConfigService getConfigService = new GetConfigService(
+ configRequestParameters, requestID);
+ policyConfig = getConfigService.getResult();
+ status = getConfigService.getResponseCode();
+ }
+ configCounter.incrementAndGet();
+ return new ResponseEntity<Collection<PolicyConfig>>(policyConfig,
+ status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP) using PolicyName")
+ @RequestMapping(value = "/getConfigByPolicyName", method = RequestMethod.POST)
+ @ResponseBody
+ @Deprecated
+ public ResponseEntity<Collection<PolicyConfig>> getConfigByPolicyName(
+ @RequestBody ConfigNameRequest configNameRequest,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ Collection<PolicyConfig> policyConfig = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "getConfigByPolicyName")) {
+ ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
+ configRequestParameters.setPolicyName(configNameRequest
+ .getPolicyName());
+ GetConfigService getConfigService = new GetConfigService(
+ configRequestParameters, requestID);
+ policyConfig = getConfigService.getResult();
+ status = getConfigService.getResponseCode();
+ }
+ configNameCounter.incrementAndGet();
+ return new ResponseEntity<Collection<PolicyConfig>>(policyConfig,
+ status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Gets the list of configuration policies from the PDP")
+ @RequestMapping(value = "/listConfig", method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity<Collection<String>> listConfig(
+ @RequestBody ConfigRequestParameters configRequestParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ Collection<String> results = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth
+ .checkPermissions(clientEncoding, requestID, "listConfig")) {
+ ListConfigService listConfigService = new ListConfigService(
+ configRequestParameters, requestID);
+ results = listConfigService.getResult();
+ status = listConfigService.getResponseCode();
+ }
+ configCounter.incrementAndGet();
+ return new ResponseEntity<Collection<String>>(results, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Gets the policy metrics from the PolicyAccessPoint(PAP)")
+ @RequestMapping(value="/getMetrics", method=RequestMethod.GET)
+ @ResponseBody
+ public ResponseEntity<MetricsResponse> getMetrics(
+ @RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) {
+ MetricsResponse response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if(PDPApiAuth.checkPermissions(clientEncoding, requestID, "getMetrics")){
+ GetMetricsService getMetricsService = new GetMetricsService(requestID);
+ response = getMetricsService.getResult();
+ status = getMetricsService.getResponseCode();
+ }
+ metricCounter.incrementAndGet();
+ return new ResponseEntity<MetricsResponse>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Sends the Events specified to the Policy Engine")
+ @RequestMapping(value = "/sendEvent", method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity<Collection<PolicyResponse>> sendEvent(
+ @RequestBody EventRequestParameters eventRequestParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ Collection<PolicyResponse> policyResponse = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "sendEvent")) {
+ SendEventService sendEventService = new SendEventService(
+ eventRequestParameters, requestID);
+ policyResponse = sendEventService.getResult();
+ status = sendEventService.getResponseCode();
+ }
+ eventCounter.incrementAndGet();
+ return new ResponseEntity<Collection<PolicyResponse>>(policyResponse,
+ status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Gets the Decision using specified decision parameters")
+ @RequestMapping(value = "/getDecision", method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity<DecisionResponse> getDecision(
+ @RequestBody DecisionRequestParameters decisionRequestParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ DecisionResponse decisionResponse = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "getDecision")) {
+ GetDecisionService getDecisionService = new GetDecisionService(
+ decisionRequestParameters, requestID);
+ decisionResponse = getDecisionService.getResult();
+ status = getDecisionService.getResponseCode();
+ }
+ decisionCounter.incrementAndGet();
+ return new ResponseEntity<DecisionResponse>(decisionResponse, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Pushes the specified policy to the PDP Group.")
+ @RequestMapping(value = "/pushPolicy", method = RequestMethod.PUT)
+ @ResponseBody
+ public ResponseEntity<String> pushPolicy(
+ @RequestBody PushPolicyParameters pushPolicyParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth
+ .checkPermissions(clientEncoding, requestID, "pushPolicy")) {
+ PushPolicyService pushPolicyService = new PushPolicyService(
+ pushPolicyParameters, requestID);
+ response = pushPolicyService.getResult();
+ status = pushPolicyService.getResponseCode();
+ }
+ pushCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Deletes the specified policy from the PDP Group or PAP.")
+ @RequestMapping(value = "/deletePolicy", method = RequestMethod.DELETE)
+ @ResponseBody
+ public ResponseEntity<String> deletePolicy(
+ @RequestBody DeletePolicyParameters deletePolicyParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "deletePolicy")) {
+ DeletePolicyService deletePolicyService = new DeletePolicyService(
+ deletePolicyParameters, requestID);
+ response = deletePolicyService.getResult();
+ status = deletePolicyService.getResponseCode();
+ }
+ deleteCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Creates a Policy based on given Policy Parameters.")
+ @RequestMapping(value = "/createPolicy", method = RequestMethod.PUT)
+ @ResponseBody
+ public ResponseEntity<String> createPolicy(
+ @RequestBody PolicyParameters policyParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "createPolicy")) {
+ CreateUpdatePolicyService createPolicyService;
+ try {
+ createPolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor().newInstance(
+ policyParameters, requestID, false);
+ response = createPolicyService.getResult();
+ status = createPolicyService.getResponseCode();
+ } catch (InstantiationException | IllegalAccessException
+ | IllegalArgumentException | InvocationTargetException e) {
+ LOGGER.error(e.getMessage());
+ response = "Problem with CreateUpdate Policy Service. ";
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
+ }
+ }
+ createPolicyCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Updates a Policy based on given Policy Parameters.")
+ @RequestMapping(value = "/updatePolicy", method = RequestMethod.PUT)
+ @ResponseBody
+ public ResponseEntity<String> updatePolicy(
+ @RequestBody PolicyParameters policyParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "updatePolicy")) {
+ CreateUpdatePolicyService updatePolicyService;
+ try {
+ updatePolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor().newInstance(
+ policyParameters, requestID, true);
+ response = updatePolicyService.getResult();
+ status = updatePolicyService.getResponseCode();
+ } catch (InstantiationException | IllegalAccessException
+ | IllegalArgumentException | InvocationTargetException e) {
+ LOGGER.error(e.getMessage());
+ response = "Problem with CreateUpdate Policy Service. ";
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
+ }
+ }
+ updatePolicyCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Creates a Dictionary Item for a specific dictionary based on given Parameters.")
+ @RequestMapping(value = "/createDictionaryItem", method = RequestMethod.PUT)
+ @ResponseBody
+ public ResponseEntity<String> createDictionaryItem(
+ @RequestBody DictionaryParameters dictionaryParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "createDictionary")) {
+ CreateUpdateDictionaryService createDictionaryService = new CreateUpdateDictionaryService(
+ dictionaryParameters, requestID, false);
+ response = createDictionaryService.getResult();
+ status = createDictionaryService.getResponseCode();
+ }
+ createDictionaryCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Updates a Dictionary Item for a specific dictionary based on given Parameters.")
+ @RequestMapping(value = "/updateDictionaryItem", method = RequestMethod.PUT)
+ @ResponseBody
+ public ResponseEntity<String> updateDictionaryItem(
+ @RequestBody DictionaryParameters dictionaryParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "updateDictionary")) {
+ CreateUpdateDictionaryService updateDictionaryService = new CreateUpdateDictionaryService(
+ dictionaryParameters, requestID, true);
+ response = updateDictionaryService.getResult();
+ status = updateDictionaryService.getResponseCode();
+ }
+ updateDictionaryCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Gets the dictionary items from the PAP")
+ @RequestMapping(value = "/getDictionaryItems", method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity<DictionaryResponse> getDictionaryItems(
+ @RequestBody DictionaryParameters dictionaryParameters,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ DictionaryResponse dictionaryResponse = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "getDictionary")) {
+ GetDictionaryService getDictionaryService = new GetDictionaryService(
+ dictionaryParameters, requestID);
+ dictionaryResponse = getDictionaryService.getResult();
+ status = getDictionaryService.getResponseCode();
+ }
+ getDictionaryCounter.incrementAndGet();
+ return new ResponseEntity<DictionaryResponse>(dictionaryResponse,
+ status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Imports Policy based on the parameters which represent the service used to create a policy Service.")
+ @RequestMapping(value = "/policyEngineImport", method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity<String> policyEngineImport(
+ @RequestParam("importParametersJson") String importParametersJson,
+ @RequestParam("file") MultipartFile file,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "policyEngineImport")) {
+ PolicyEngineImportService policyEngineImportService = new PolicyEngineImportService(
+ importParametersJson, file, requestID);
+ response = policyEngineImportService.getResult();
+ status = policyEngineImportService.getResponseCode();
+ }
+ policyEngineImportCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Creates a Config Policy based on given Policy Parameters.")
+ @RequestMapping(value = "/createConfig", method = RequestMethod.PUT)
+ @ResponseBody
+ @Deprecated
+ public ResponseEntity<String> createConfig(
+ @RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "createPolicy")) {
+ CreateUpdateConfigPolicyService createPolicyService = new CreateUpdateConfigPolicyService(
+ configPolicyAPIRequest, requestID, false);
+ response = createPolicyService.getResult();
+ status = createPolicyService.getResponseCode();
+ }
+ deprecatedCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Updates a Config Policy based on given Policy Parameters.")
+ @RequestMapping(value = "/updateConfig", method = RequestMethod.PUT)
+ @ResponseBody
+ @Deprecated
+ public ResponseEntity<String> updateConfig(
+ @RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "updatePolicy")) {
+ CreateUpdateConfigPolicyService updatePolicyService = new CreateUpdateConfigPolicyService(
+ configPolicyAPIRequest, requestID, true);
+ response = updatePolicyService.getResult();
+ status = updatePolicyService.getResponseCode();
+ }
+ deprecatedCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Creates a Config Firewall Policy")
+ @RequestMapping(value = "/createFirewallConfig", method = RequestMethod.PUT)
+ @ResponseBody
+ @Deprecated
+ public ResponseEntity<String> createFirewallConfig(
+ @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "createPolicy")) {
+ CreateUpdateFirewallPolicyService createFirewallPolicyService = new CreateUpdateFirewallPolicyService(
+ configFirewallPolicyAPIRequest, requestID, false);
+ response = createFirewallPolicyService.getResult();
+ status = createFirewallPolicyService.getResponseCode();
+ }
+ deprecatedCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") })
+ @ApiOperation(value = "Updates a Config Firewall Policy")
+ @RequestMapping(value = "/updateFirewallConfig", method = RequestMethod.PUT)
+ @ResponseBody
+ @Deprecated
+ public ResponseEntity<String> updateFirewallConfig(
+ @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest,
+ @RequestHeader(value = "ClientAuth", required = true) String clientEncoding,
+ @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) {
+ String response = null;
+ HttpStatus status = HttpStatus.UNAUTHORIZED;
+ // Check Permissions.
+ if (PDPApiAuth.checkPermissions(clientEncoding, requestID,
+ "updatePolicy")) {
+ CreateUpdateFirewallPolicyService updateFirewallPolicyService = new CreateUpdateFirewallPolicyService(
+ configFirewallPolicyAPIRequest, requestID, true);
+ response = updateFirewallPolicyService.getResult();
+ status = updateFirewallPolicyService.getResponseCode();
+ }
+ deprecatedCounter.incrementAndGet();
+ return new ResponseEntity<String>(response, status);
+ }
+
+ @ApiOperation(value = "Gets the API Services usage Information")
+ @ApiIgnore
+ @RequestMapping(value = "/count", method = RequestMethod.GET)
+ public String getCount() {
+ return "Total Config Calls : " + configCounter + "\n"
+ + "Total Config calls made using Policy File Name: "
+ + configNameCounter + "\n" + "Total Event Calls : "
+ + eventCounter + "\nTotal Decision Calls: " + decisionCounter
+ + "\nTotal Push policy Calls: " + pushCounter
+ + "\nTotal Delete Policy Calls: " + deleteCounter
+ + "\nTotal Create Policy Calls: " + createPolicyCounter
+ + "\nTotal Update Policy Calls: " + updatePolicyCounter
+ + "\nTotal Create Dictionary Calls: " + createDictionaryCounter
+ + "\nTotal Update Dictionary Calls: " + updateDictionaryCounter
+ + "\nTotal Get Dictionary Calls: " + getDictionaryCounter
+ + "\nTotal PolicyEngine Import Calls: "
+ + policyEngineImportCounter
+ + "\nTotal Deprecated Policy Calls: " + deprecatedCounter
+ + "\nTotal Metrics Calls:" + metricCounter;
+ }
+
+ @ExceptionHandler({ HttpMessageNotReadableException.class })
+ public ResponseEntity<String> messageNotReadableExceptionHandler(
+ HttpServletRequest req, HttpMessageNotReadableException exception) {
+ LOGGER.error("Request not readable: {}", exception);
+ StringBuilder message = new StringBuilder();
+ message.append(exception.getMessage());
+ if (exception.getCause() != null) {
+ message.append(" Reason Caused: "
+ + exception.getCause().getMessage());
+ }
+ return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST);
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java
new file mode 100644
index 000000000..4ae368ae7
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java
@@ -0,0 +1,80 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.models;
+
+import io.swagger.annotations.ApiModel;
+
+import java.io.Serializable;
+
+@ApiModel
+public class ConfigFirewallPolicyAPIRequest implements Serializable{
+ private static final long serialVersionUID = -7460640390070215401L;
+
+ private String policyName = null;
+ private String policyScope = null;
+ private String firewallJson = null;
+ private String riskType = "default";
+ private String riskLevel = "5";
+ private String guard = "false";
+ private String ttlDate = null;
+
+ public String getPolicyName() {
+ return policyName;
+ }
+ public String getPolicyScope() {
+ return policyScope;
+ }
+ public String getFirewallJson() {
+ return firewallJson;
+ }
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+ public void setPolicyScope(String policyScope) {
+ this.policyScope = policyScope;
+ }
+ public void setFirewallJson(String firewallJson) {
+ this.firewallJson = firewallJson;
+ }
+ public String getRiskType() {
+ return riskType;
+ }
+ public void setRiskType(String riskType) {
+ this.riskType = riskType;
+ }
+ public String getRiskLevel() {
+ return riskLevel;
+ }
+ public void setRiskLevel(String riskLevel) {
+ this.riskLevel = riskLevel;
+ }
+ public String getGuard() {
+ return guard;
+ }
+ public void setGuard(String guard) {
+ this.guard = guard;
+ }
+ public String getTtlDate() {
+ return ttlDate;
+ }
+ public void setTtlDate(String ttlDate) {
+ this.ttlDate = ttlDate;
+ }
+} \ No newline at end of file
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java
new file mode 100644
index 000000000..91881a3b2
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java
@@ -0,0 +1,39 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.models;
+
+import io.swagger.annotations.ApiModel;
+
+import java.io.Serializable;
+
+@ApiModel
+public class ConfigNameRequest implements Serializable{
+ private static final long serialVersionUID = 4487978240532425305L;
+
+ private String policyName = null;
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+ public String getPolicyName() {
+ return policyName;
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java
new file mode 100644
index 000000000..ed5d0ccaf
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java
@@ -0,0 +1,188 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.models;
+
+import io.swagger.annotations.ApiModel;
+
+import java.io.Serializable;
+import java.util.Map;
+
+@ApiModel
+public class ConfigPolicyAPIRequest implements Serializable{
+ private static final long serialVersionUID = -4103391389984557025L;
+
+ private String policyScope = null;
+ private String policyName = null;
+ private String policyDescription = null;
+ private String ecompName = null;
+ private String configName = null;
+ private Map<String,String> configAttributes = null;
+ private String configType = null;
+ private String body = null;
+ private String riskType = "default";
+ private String riskLevel = "5";
+ private String guard = "false";
+ private String ttlDate = null;
+
+ /**
+ * @return the policyScope
+ */
+ public String getPolicyScope() {
+ return policyScope;
+ }
+ /**
+ * @return the policyName
+ */
+ public String getPolicyName() {
+ return policyName;
+ }
+ /**
+ * @return the policyDescription
+ */
+ public String getPolicyDescription() {
+ return policyDescription;
+ }
+ /**
+ * @return the ecompName
+ */
+ public String getEcompName() {
+ return ecompName;
+ }
+ /**
+ * @return the configName
+ */
+ public String getConfigName() {
+ return configName;
+ }
+ /**
+ * @return the configAttributes
+ */
+ public Map<String, String> getConfigAttributes() {
+ return configAttributes;
+ }
+ /**
+ * @return the configType
+ */
+ public String getConfigType() {
+ return configType;
+ }
+ /**
+ * @return the body
+ */
+ public String getBody() {
+ return body;
+ }
+ /**
+ * @param policyScope the policyScope to set
+ */
+ public void setPolicyScope(String policyScope) {
+ this.policyScope = policyScope;
+ }
+ /**
+ * @param policyName the policyName to set
+ */
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+ /**
+ * @param policyDescription the policyDescription to set
+ */
+ public void setPolicyDescription(String policyDescription) {
+ this.policyDescription = policyDescription;
+ }
+ /**
+ * @param ecompName the ecompName to set
+ */
+ public void setEcompName(String ecompName) {
+ this.ecompName = ecompName;
+ }
+ /**
+ * @param configName the configName to set
+ */
+ public void setConfigName(String configName) {
+ this.configName = configName;
+ }
+ /**
+ * @param configAttributes the configAttributes to set
+ */
+ public void setConfigAttributes(Map<String, String> configAttributes) {
+ this.configAttributes = configAttributes;
+ }
+ /**
+ * @param configType the configType to set
+ */
+ public void setConfigType(String configType) {
+ this.configType = configType;
+ }
+ /**
+ * @param body the body to set
+ */
+ public void setBody(String body) {
+ this.body = body;
+ }
+ /**
+ * @return the guard
+ */
+ public String getGuard() {
+ return guard;
+ }
+ /**
+ * @param guard the guard to set
+ */
+ public void setGuard(String guard) {
+ this.guard = guard;
+ }
+ /**
+ * @return the riskLevel
+ */
+ public String getRiskLevel() {
+ return riskLevel;
+ }
+ /**
+ * @param riskLevel the riskLevel to set
+ */
+ public void setRiskLevel(String riskLevel) {
+ this.riskLevel = riskLevel;
+ }
+ /**
+ * @return the ttlDate
+ */
+ public String getTtlDate() {
+ return ttlDate;
+ }
+ /**
+ * @param ttlDate the ttlDate to set
+ */
+ public void setTtlDate(String ttlDate) {
+ this.ttlDate = ttlDate;
+ }
+ /**
+ * @return the riskType
+ */
+ public String getRiskType() {
+ return riskType;
+ }
+ /**
+ * @param riskType the riskType to set
+ */
+ public void setRiskType(String riskType) {
+ this.riskType = riskType;
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java
new file mode 100644
index 000000000..2301d003c
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java
@@ -0,0 +1,159 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.models;
+
+import java.util.Map;
+
+import org.openecomp.policy.api.DecisionResponse;
+import org.openecomp.policy.api.PolicyConfigStatus;
+import org.openecomp.policy.api.PolicyDecision;
+import org.openecomp.policy.api.PolicyResponse;
+import org.openecomp.policy.api.PolicyResponseStatus;
+import org.openecomp.policy.api.PolicyType;
+import org.openecomp.policy.models.APIConfigResponse;
+
+public class PDPResponse implements APIConfigResponse, PolicyResponse, DecisionResponse{
+ private String policyConfigMessage;
+ private PolicyConfigStatus policyConfigStatus;
+ private PolicyType type;
+ private String config;
+ private String policyName;
+ private String policyVersion;
+ private Map<String, String> matchingConditions;
+ private Map<String, String> responseAttributes;
+ private Map<String, String> property;
+ private PolicyResponseStatus policyResponseStatus;
+ private String policyResponseMessage;
+ private Map<String,String> actionAdvised;
+ private Map<String,String> actionTaken;
+ private Map<String,String> requestAttributes;
+ private PolicyDecision policyDecision;
+ private String details;
+
+ public void setStatus(String message, PolicyResponseStatus policyResponseStatus, PolicyConfigStatus policyConfigStatus) {
+ this.policyConfigMessage = message;
+ this.policyResponseMessage = message;
+ this.policyResponseStatus = policyResponseStatus;
+ this.policyConfigStatus = policyConfigStatus;
+ }
+ public String getConfig() {
+ return config;
+ }
+ public void setConfig(String config) {
+ this.config = config;
+ }
+ public PolicyType getType() {
+ return type;
+ }
+ public void setType(PolicyType type) {
+ this.type = type;
+ }
+ public PolicyConfigStatus getPolicyConfigStatus() {
+ return policyConfigStatus;
+ }
+ public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) {
+ this.policyConfigStatus = policyConfigStatus;
+ }
+ public String getPolicyConfigMessage() {
+ return policyConfigMessage;
+ }
+ public void setPolicyConfigMessage(String policyConfigMessage) {
+ this.policyConfigMessage = policyConfigMessage;
+ }
+ public Map<String, String> getProperty() {
+ return property;
+ }
+ public void setProperty(Map<String, String> property) {
+ this.property = property;
+ }
+ public String getPolicyName(){
+ return policyName;
+ }
+ public void setPolicyName(String policyName){
+ this.policyName = policyName;
+ }
+ public String getPolicyVersion(){
+ return policyVersion;
+ }
+ public void setPolicyVersion(String policyVersion){
+ this.policyVersion = policyVersion;
+ }
+ public Map<String, String> getMatchingConditions(){
+ return matchingConditions;
+ }
+ public void setMatchingConditions(Map<String, String> matchingConditions){
+ this.matchingConditions = matchingConditions;
+ }
+ public void setResponseAttributes(Map<String,String> responseAttributes){
+ this.responseAttributes = responseAttributes;
+ }
+ public Map<String,String> getResponseAttributes(){
+ return responseAttributes;
+ }
+ public void setPolicyResponseStatus(PolicyResponseStatus policyResponseStatus) {
+ this.policyResponseStatus = policyResponseStatus;
+ }
+ @Override
+ public PolicyResponseStatus getPolicyResponseStatus() {
+ return policyResponseStatus;
+ }
+ public void setDecision(PolicyDecision policyDecision){
+ this.policyDecision = policyDecision;
+ }
+ @Override
+ public PolicyDecision getDecision() {
+ return policyDecision;
+ }
+ public void setDetails(String details){
+ this.details = details;
+ }
+ @Override
+ public String getDetails() {
+ return details;
+ }
+ public void setActionAdvised(Map<String, String> actionAdvised) {
+ this.actionAdvised = actionAdvised;
+ }
+ @Override
+ public Map<String, String> getActionAdvised() {
+ return actionAdvised;
+ }
+ public void setActionTaken(Map<String, String> actionTaken) {
+ this.actionTaken = actionTaken;
+ }
+ @Override
+ public Map<String, String> getActionTaken() {
+ return actionTaken;
+ }
+ public void setRequestAttributes(Map<String, String> requestAttributes) {
+ this.requestAttributes = requestAttributes;
+ }
+ @Override
+ public Map<String, String> getRequestAttributes() {
+ return requestAttributes;
+ }
+ public void setPolicyResponseMessage(String policyResponseMessage) {
+ this.policyResponseMessage = policyResponseMessage;
+ }
+ @Override
+ public String getPolicyResponseMessage() {
+ return policyResponseMessage;
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java
new file mode 100644
index 000000000..729ffbb6f
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.models;
+
+import io.swagger.annotations.ApiModel;
+
+import java.util.Map;
+
+import org.openecomp.policy.api.PolicyConfigStatus;
+import org.openecomp.policy.api.PolicyType;
+import org.openecomp.policy.models.APIConfigResponse;
+
+@ApiModel
+public class PolicyConfig implements APIConfigResponse{
+ private String policyConfigMessage;
+ private PolicyConfigStatus policyConfigStatus;
+ private PolicyType type;
+ private String config;
+ private String policyName;
+ private String policyVersion;
+ private Map<String, String> matchingConditions;
+ private Map<String, String> responseAttributes;
+ private Map<String, String> property;
+ public String getConfig() {
+ return config;
+ }
+ public void setConfig(String config) {
+ this.config = config;
+ }
+ public PolicyType getType() {
+ return type;
+ }
+ public void setType(PolicyType type) {
+ this.type = type;
+ }
+ public PolicyConfigStatus getPolicyConfigStatus() {
+ return policyConfigStatus;
+ }
+ public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) {
+ this.policyConfigStatus = policyConfigStatus;
+ }
+ public String getPolicyConfigMessage() {
+ return policyConfigMessage;
+ }
+ public void setPolicyConfigMessage(String policyConfigMessage) {
+ this.policyConfigMessage = policyConfigMessage;
+ }
+ public Map<String, String> getProperty() {
+ return property;
+ }
+ public void setProperty(Map<String, String> property) {
+ this.property = property;
+ }
+ public String getPolicyName(){
+ return policyName;
+ }
+ public void setPolicyName(String policyName){
+ this.policyName = policyName;
+ }
+ public String getPolicyVersion(){
+ return policyVersion;
+ }
+ public void setPolicyVersion(String policyVersion){
+ this.policyVersion = policyVersion;
+ }
+ public Map<String, String> getMatchingConditions(){
+ return matchingConditions;
+ }
+ public void setMatchingConditions(Map<String, String> matchingConditions){
+ this.matchingConditions = matchingConditions;
+ }
+ public void setResponseAttributes(Map<String,String> responseAttributes){
+ this.responseAttributes = responseAttributes;
+ }
+ public Map<String,String> getResponseAttributes(){
+ return responseAttributes;
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java
new file mode 100644
index 000000000..14c536605
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java
@@ -0,0 +1,105 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.Map;
+
+import org.openecomp.policy.api.AttributeType;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * Action Policy Implementation.
+ *
+ * @version 0.1
+ */
+public class ActionPolicyService {
+ private static Logger LOGGER = FlexLogger.getLogger(ActionPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private PolicyParameters policyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private Map<String,String> componentAttributes = null;
+ private String actionAttribute = null;
+ private String actionPerformer = null;
+
+ public ActionPolicyService(String policyScope, String policyName,
+ PolicyParameters policyParameters) {
+ this.policyParameters = policyParameters;
+ this.policyName = policyName;
+ this.policyScope = policyScope;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ if(policyParameters.getAttributes()==null || policyParameters.getAttributes().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given.";
+ return false;
+ }
+ componentAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING);
+ if (componentAttributes==null||componentAttributes.isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given.";
+ return false;
+ }
+ actionAttribute = policyParameters.getActionAttribute();
+ if (actionAttribute==null||actionAttribute.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Attribute given.";
+ return false;
+ }
+ actionPerformer = policyParameters.getActionPerformer();
+ if (actionPerformer==null||actionPerformer.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Performer given.";
+ return false;
+ }
+ if(!"PEP".equalsIgnoreCase(actionPerformer)&& !"PDP".equalsIgnoreCase(actionPerformer)){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Performer given.";
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException {
+ String response = null;
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ // Create Policy
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyParameters.getPolicyDescription(),
+ componentAttributes, policyParameters.getDynamicRuleAlgorithmLabels(), policyParameters.getDynamicRuleAlgorithmFunctions(),
+ policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmField2(), actionPerformer, actionAttribute, updateFlag, policyScope, 0);
+ // send Json to PAP
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Action"}, policyParameters.getRequestID(), "Action");
+ LOGGER.info(response);
+ return response;
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java
new file mode 100644
index 000000000..971f2fd35
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java
@@ -0,0 +1,97 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.Map;
+
+import org.openecomp.policy.api.AttributeType;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * BRMS Param Policy Implementation.
+ *
+ * @version 0.1
+ */
+public class BRMSParamPolicyService{
+ private static Logger LOGGER = FlexLogger.getLogger(BRMSParamPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private PolicyParameters policyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private String date = null;
+ private boolean levelCheck = false;
+ private Map<AttributeType, Map<String, String>> drlRuleAndUIParams = null;
+
+ public BRMSParamPolicyService(String policyName, String policyScope,
+ PolicyParameters policyParameters, String date) {
+ this.policyParameters = policyParameters;
+ this.policyName = policyName;
+ this.policyScope = policyScope;
+ this.date = date;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel());
+ if(!levelCheck){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
+ return false;
+ }
+ drlRuleAndUIParams = policyParameters.getAttributes();
+ if(drlRuleAndUIParams==null || drlRuleAndUIParams.isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Rule Attributes given.";
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException {
+ String response = null;
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ // Create Policy
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Param",policyName, policyParameters.getPolicyDescription(),
+ "BRMS_PARAM_RULE",updateFlag,policyScope,
+ drlRuleAndUIParams.get(AttributeType.MATCHING), 0, "DROOLS",
+ null, drlRuleAndUIParams.get(AttributeType.RULE), policyParameters.getRiskLevel(),
+ policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date, policyParameters.getControllerName(), policyParameters.getDependencyNames());
+ // Send JSON to PAP
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigBrmsParam");
+ LOGGER.info(response);
+ return response;
+ }
+
+} \ No newline at end of file
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java
new file mode 100644
index 000000000..c68b1695b
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java
@@ -0,0 +1,106 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.Map;
+
+import org.openecomp.policy.api.AttributeType;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.utils.PolicyUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * BRMS RAW Policy Implementation.
+ *
+ * @version 0.1
+ */
+public class BRMSRawPolicyService{
+ private static Logger LOGGER = FlexLogger.getLogger(BRMSRawPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private PolicyParameters policyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private String date = null;
+ private boolean levelCheck = false;
+ private String brmsRawBody = null;
+
+ public BRMSRawPolicyService(String policyName, String policyScope,
+ PolicyParameters policyParameters, String date) {
+ this.policyParameters = policyParameters;
+ this.policyName = policyName;
+ this.policyScope = policyScope;
+ this.date = date;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ brmsRawBody = policyParameters.getConfigBody();
+ if(brmsRawBody==null || brmsRawBody.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Rule Body given";
+ return false;
+ }
+ message = PolicyUtils.brmsRawValidate(brmsRawBody);
+ if(message.contains("[ERR")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Raw rule given is invalid" +message;
+ return false;
+ }
+ levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel());
+ if(!levelCheck){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException {
+ String response = null;
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ Map<String,String> ruleAttributes = null;
+ if(policyParameters.getAttributes()!=null){
+ ruleAttributes = policyParameters.getAttributes().get(AttributeType.RULE);
+ }
+ // Create Policy
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Raw",policyName,policyParameters.getPolicyDescription(),
+ "BRMS_RAW_RULE",updateFlag,policyScope, ruleAttributes, 0, "DROOLS",
+ brmsRawBody, policyParameters.getRiskLevel(),
+ policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date, policyParameters.getControllerName(), policyParameters.getDependencyNames());
+ // Send JSON to PAP
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigBrmsRaw");
+ LOGGER.info(response);
+ return response;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java
new file mode 100644
index 000000000..a85533be8
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java
@@ -0,0 +1,115 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import javax.json.JsonException;
+import javax.json.JsonObject;
+
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * Closed Loop Fault Policy Implementation.
+ *
+ * @version 0.1
+ */
+public class ClosedLoopFaultPolicyService{
+ private static Logger LOGGER = FlexLogger.getLogger(ClosedLoopFaultPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private PolicyParameters policyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private String date = null;
+ private JsonObject configBody = null;
+
+ public ClosedLoopFaultPolicyService(String policyName, String policyScope,
+ PolicyParameters policyParameters, String date) {
+ this.policyParameters = policyParameters;
+ this.policyName = policyName;
+ this.policyScope = policyScope;
+ this.date = date;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ if(policyParameters.getConfigBody()==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
+ return false;
+ }
+ if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
+ return false;
+ }
+ try{
+ configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody());
+ } catch(JsonException| IllegalStateException e){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException {
+ String response = null;
+ String operation = null;
+ String oldPolicyName = null;
+ if (updateFlag){
+ operation = "update";
+ if (policyName.endsWith("_Draft")) {
+ oldPolicyName = policyName + "_Draft.1";
+ }
+ } else {
+ operation = "create";
+ }
+ boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel());
+ // get values and attributes from the JsonObject
+ String ecompName = configBody.get("ecompname").toString().replace("\"", "");
+ String jsonBody = configBody.toString();
+ if (ecompName==null||ecompName.equals("")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
+ LOGGER.error(message);
+ return message;
+ }
+ if (!levelCheck){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
+ LOGGER.error(message);
+ return message;
+ }
+ // Create Policy.
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_Fault", policyName, policyParameters.getPolicyDescription(), ecompName,
+ jsonBody, false, oldPolicyName, null, updateFlag, policyScope, 0, policyParameters.getRiskLevel(),
+ policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date);
+ //send JSON object to PAP
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigClosedLoop");
+ return response;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java
new file mode 100644
index 000000000..15a2c3abc
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java
@@ -0,0 +1,111 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import javax.json.JsonException;
+import javax.json.JsonObject;
+
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * Closed Loop PM policy Implementation.
+ *
+ * @version 0.1
+ */
+public class ClosedLoopPMPolicyService{
+ private static Logger LOGGER = FlexLogger.getLogger(ClosedLoopPMPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private PolicyParameters policyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private String date = null;
+ private JsonObject configBody = null;
+
+ public ClosedLoopPMPolicyService(String policyName, String policyScope,
+ PolicyParameters policyParameters, String date) {
+ this.policyParameters = policyParameters;
+ this.policyName = policyName;
+ this.policyScope = policyScope;
+ this.date = date;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ if(policyParameters.getConfigBody()==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
+ return false;
+ }
+ if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
+ return false;
+ }
+ try{
+ configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody());
+ } catch(JsonException| IllegalStateException e){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException{
+ String response = null;
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel());
+ // get values and attributes from the JsonObject
+ String ecompName = configBody.get("ecompname").toString().replace("\"", "");
+ String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", "");
+ String jsonBody = configBody.toString();
+ if (ecompName==null||ecompName.equals("")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
+ LOGGER.error(message);
+ return message;
+ }
+ if (!levelCheck){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
+ LOGGER.error(message);
+ return message;
+ }
+ // Create Policy.
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_PM", policyName, policyParameters.getPolicyDescription(), ecompName,
+ jsonBody, false, null, serviceType, updateFlag, policyScope, 0, policyParameters.getRiskLevel(),
+ policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date);
+ //send JSON object to PAP
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigClosedLoop");
+ return response;
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java
new file mode 100644
index 000000000..8edd1ac61
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java
@@ -0,0 +1,136 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.Map;
+
+import org.openecomp.policy.api.AttributeType;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.utils.PolicyUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * Config Base Policy Implementation.
+ *
+ * @version 0.1
+ */
+public class ConfigPolicyService {
+ private static Logger LOGGER = FlexLogger.getLogger(ConfigPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private PolicyParameters policyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private String date = null;
+ private boolean levelCheck = false;
+ private String ecompName = null;
+ private String configName = null;
+
+ public ConfigPolicyService(String policyName, String policyScope,
+ PolicyParameters policyParameters, String date) {
+ this.policyParameters = policyParameters;
+ this.policyName = policyName;
+ this.policyScope = policyScope;
+ this.date = date;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ if(policyParameters.getConfigBody()==null || policyParameters.getConfigBody().trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
+ return false;
+ }
+ if(policyParameters.getConfigBodyType()==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given.";
+ return false;
+ }
+ levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel());
+ if (!levelCheck){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
+ return false;
+ }
+ ecompName = policyParameters.getEcompName();
+ configName = policyParameters.getConfigName();
+ if(ecompName==null || ecompName.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.";
+ return false;
+ }
+ if(configName==null || configName.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.";
+ return false;
+ }
+ message = PolicyUtils.emptyPolicyValidator(ecompName);
+ if(!message.contains("success")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
+ return false;
+ }
+ message = PolicyUtils.emptyPolicyValidator(configName);
+ if(!message.contains("success")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException {
+ String response = null;
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ String configType = policyParameters.getConfigBodyType().toString();
+ String body = policyParameters.getConfigBody();
+ String configBody = null;
+ //check body for JSON form and remove single quotes if present
+ if (configType.equalsIgnoreCase("JSON")) {
+ if (body.contains("'")) {
+ configBody = body.replace("'", "\"");
+ } else {
+ configBody = body;
+ }
+ } else {
+ configBody = body;
+ }
+ Map<String,String> configAttributes = null;
+ if(policyParameters.getAttributes()!=null){
+ configAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING);
+ }
+ // create Policy.
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Base", policyName, policyParameters.getPolicyDescription(), ecompName, configName, configAttributes, configType,
+ configBody, updateFlag, policyScope,0, policyParameters.getRiskLevel(),policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date);
+ // Send Json to PAP.
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "Config");
+ LOGGER.info(response);
+ return response;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java
new file mode 100644
index 000000000..e26fae18a
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java
@@ -0,0 +1,102 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.policy.api.AttributeType;
+import org.openecomp.policy.api.PolicyClass;
+import org.openecomp.policy.api.PolicyConfigType;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.api.PolicyType;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.models.ConfigPolicyAPIRequest;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class CreateUpdateConfigPolicyService {
+ private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateConfigPolicyService.class.getName());
+
+ private String response = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+
+ public CreateUpdateConfigPolicyService(
+ ConfigPolicyAPIRequest configPolicyAPIRequest, String requestID,
+ boolean updateFlag) {
+ try{
+ run(configPolicyAPIRequest, requestID, updateFlag);
+ }catch(PolicyException e){
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void run(ConfigPolicyAPIRequest configPolicyAPIRequest,
+ String requestID, boolean updateFlag) throws PolicyException{
+ PolicyParameters policyParameters = new PolicyParameters();
+ policyParameters.setPolicyClass(PolicyClass.Config);
+ policyParameters.setPolicyConfigType(PolicyConfigType.Base);
+ if(configPolicyAPIRequest.getPolicyScope()==null|| configPolicyAPIRequest.getPolicyScope().trim().isEmpty()){
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ if(configPolicyAPIRequest.getPolicyName()==null|| configPolicyAPIRequest.getPolicyName().trim().isEmpty()){
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ policyParameters.setPolicyName(configPolicyAPIRequest.getPolicyScope()+"."+configPolicyAPIRequest.getPolicyName());
+ policyParameters.setPolicyDescription(configPolicyAPIRequest.getPolicyDescription());
+ policyParameters.setEcompName(configPolicyAPIRequest.getEcompName());
+ policyParameters.setConfigName(configPolicyAPIRequest.getConfigName());
+ Map<AttributeType, Map<String, String>> attributes = new HashMap<AttributeType, Map<String, String>>();
+ attributes.put(AttributeType.MATCHING, configPolicyAPIRequest.getConfigAttributes());
+ policyParameters.setAttributes(attributes);
+ policyParameters.setConfigBodyType(PolicyType.valueOf(configPolicyAPIRequest.getConfigType()));
+ policyParameters.setConfigBody(configPolicyAPIRequest.getBody());
+ policyParameters.setRiskLevel(configPolicyAPIRequest.getRiskLevel());
+ policyParameters.setRiskType(configPolicyAPIRequest.getRiskType());
+ policyParameters.setGuard(Boolean.parseBoolean(configPolicyAPIRequest.getGuard()));
+ try {
+ policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configPolicyAPIRequest.getTtlDate()));
+ } catch (ParseException e) {
+ LOGGER.warn("Error Parsing date given " + configPolicyAPIRequest.getTtlDate());
+ policyParameters.setTtlDate(null);
+ }
+ CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag);
+ status = createUpdatePolicyService.getResponseCode();
+ response = createUpdatePolicyService.getResult();
+ }
+
+ public String getResult() {
+ return response;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java
new file mode 100644
index 000000000..1c3049da3
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java
@@ -0,0 +1,156 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.io.ByteArrayInputStream;
+import java.util.UUID;
+
+import javax.json.JsonException;
+import javax.json.JsonObject;
+
+import org.openecomp.policy.api.DictionaryParameters;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class CreateUpdateDictionaryService {
+ private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateDictionaryService.class.getName());
+
+ private String dictionaryResult = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private String message = null;
+ private Boolean updateFlag = false;
+ private DictionaryParameters dictionaryParameters = null;
+
+ public CreateUpdateDictionaryService(
+ DictionaryParameters dictionaryParameters, String requestID,
+ boolean updateFlag) {
+ this.updateFlag = updateFlag;
+ this.dictionaryParameters = dictionaryParameters;
+ if(dictionaryParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.dictionaryParameters.setRequestID(requestUUID);
+ }
+ try{
+ run();
+ specialCheck();
+ }catch(PolicyException e){
+ dictionaryResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void specialCheck() {
+ if(dictionaryResult== null || dictionaryResult.contains("BAD REQUEST")||dictionaryResult.contains("PE300")){
+ status = HttpStatus.BAD_REQUEST;
+ } else if (dictionaryResult.contains("Policy Exist Error")) {
+ status = HttpStatus.CONFLICT;
+ } else if (dictionaryResult.contains("PE200")){
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
+ }
+ }
+
+ private void run() throws PolicyException{
+ // Check Validation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ // Get Result.
+ try{
+ status = HttpStatus.OK;
+ dictionaryResult = processResult();
+ }catch (Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyException(e);
+ }
+ }
+
+ private String processResult() throws PolicyException{
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ JsonObject json = null;
+ try{
+ json = PolicyApiUtils.stringToJsonObject(dictionaryParameters.getDictionaryJson());
+ } catch(JsonException| IllegalStateException e){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson();
+ LOGGER.error(message);
+ return message;
+ }
+ String dictionaryFields = json.toString();
+ PAPServices papServices = new PAPServices();
+ String result = (String) papServices.callPAP(new ByteArrayInputStream(dictionaryFields.getBytes()), new String[] {"operation="+operation, "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem");
+ return result;
+ }
+
+ private boolean getValidation() {
+ if(dictionaryParameters==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Dictionary Parameters are not given.";
+ return false;
+ }
+ if(dictionaryParameters.getDictionaryType()==null || dictionaryParameters.getDictionaryType().toString().trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given.";
+ return false;
+ }
+ if(dictionaryParameters.getDictionary()==null || dictionaryParameters.getDictionary().trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given.";
+ return false;
+ }
+ if(dictionaryParameters.getDictionaryJson()==null || dictionaryParameters.getDictionaryJson().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary JSON given.";
+ return false;
+ }
+ if (updateFlag && dictionaryParameters.getDictionary().equalsIgnoreCase("MicroServiceDictionary")){
+ if (!dictionaryParameters.getDictionaryJson().contains("initialFields")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Mising the required field initialFields.";
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public String getResult() {
+ return dictionaryResult;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java
new file mode 100644
index 000000000..b547f8dfe
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java
@@ -0,0 +1,92 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+
+import org.openecomp.policy.api.PolicyClass;
+import org.openecomp.policy.api.PolicyConfigType;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class CreateUpdateFirewallPolicyService {
+ private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateFirewallPolicyService.class.getName());
+
+ private String response = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+
+ public CreateUpdateFirewallPolicyService(
+ ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest,
+ String requestID, boolean updateFlag) {
+ try{
+ run(configFirewallPolicyAPIRequest, requestID, updateFlag);
+ }catch(PolicyException e){
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void run(
+ ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest,
+ String requestID, boolean updateFlag) throws PolicyException{
+ PolicyParameters policyParameters = new PolicyParameters();
+ policyParameters.setPolicyClass(PolicyClass.Config);
+ policyParameters.setPolicyConfigType(PolicyConfigType.Firewall);
+ if(configFirewallPolicyAPIRequest.getPolicyScope()==null|| configFirewallPolicyAPIRequest.getPolicyScope().trim().isEmpty()){
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ if(configFirewallPolicyAPIRequest.getPolicyName()==null|| configFirewallPolicyAPIRequest.getPolicyName().trim().isEmpty()){
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ policyParameters.setPolicyName(configFirewallPolicyAPIRequest.getPolicyScope()+"."+configFirewallPolicyAPIRequest.getPolicyName());
+ policyParameters.setConfigBody(configFirewallPolicyAPIRequest.getFirewallJson());
+ policyParameters.setRiskLevel(configFirewallPolicyAPIRequest.getRiskLevel());
+ policyParameters.setRiskType(configFirewallPolicyAPIRequest.getRiskType());
+ policyParameters.setGuard(Boolean.parseBoolean(configFirewallPolicyAPIRequest.getGuard()));
+ try {
+ policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configFirewallPolicyAPIRequest.getTtlDate()));
+ } catch (NullPointerException | ParseException e) {
+ LOGGER.warn("Error Parsing date given " + configFirewallPolicyAPIRequest.getTtlDate());
+ policyParameters.setTtlDate(null);
+ }
+ CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag);
+ status = createUpdatePolicyService.getResponseCode();
+ response = createUpdatePolicyService.getResult();
+ }
+
+ public String getResult() {
+ return response;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+} \ No newline at end of file
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java
new file mode 100644
index 000000000..73f9e7448
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import org.openecomp.policy.api.PolicyException;
+import org.springframework.http.HttpStatus;
+
+public interface CreateUpdatePolicyService {
+
+ public void run() throws PolicyException;
+
+ public String processResult() throws PolicyException;
+
+ public String getResult();
+
+ public HttpStatus getResponseCode();
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java
new file mode 100644
index 000000000..4032a8a7f
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java
@@ -0,0 +1,294 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.UUID;
+
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.utils.PolicyUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService {
+ private static Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyService.class.getName());
+
+ private String policyResult = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private Boolean updateFlag = false;
+ private String message = null;
+ private PolicyParameters policyParameters = new PolicyParameters();
+ private String policyName = null;
+ private String policyScope = null;
+ private String date = null;
+
+ public CreateUpdatePolicyServiceImpl(PolicyParameters policyParameters,
+ String requestID, boolean updateFlag) {
+ this.updateFlag = updateFlag;
+ this.policyParameters = policyParameters;
+ if(policyParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.policyParameters.setRequestID(requestUUID);
+ }
+ try{
+ run();
+ specialCheck();
+ }catch(PolicyException e){
+ policyResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ public void run() throws PolicyException{
+ // Check Validation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ // Get Result.
+ try{
+ status = HttpStatus.OK;
+ policyResult = processResult();
+ }catch (Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyException(e);
+ }
+ }
+
+ @SuppressWarnings("incomplete-switch")
+ public String processResult() throws PolicyException{
+ String response = null;
+ if(policyParameters.getPolicyConfigType()!=null){
+ // This is a Config Type Policy.
+ switch(policyParameters.getPolicyConfigType()){
+ case BRMS_PARAM:
+ BRMSParamPolicyService bRMSParamPolicyService = new BRMSParamPolicyService(policyName, policyScope, policyParameters, date);
+ // Check Validation.
+ if(!bRMSParamPolicyService.getValidation()){
+ LOGGER.error(bRMSParamPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return bRMSParamPolicyService.getMessage();
+ }
+ // Get Result.
+ response = bRMSParamPolicyService.getResult(updateFlag);
+ break;
+ case BRMS_RAW:
+ BRMSRawPolicyService bRMSRawPolicyService = new BRMSRawPolicyService(policyName, policyScope, policyParameters, date);
+ // Check Validation.
+ if(!bRMSRawPolicyService.getValidation()){
+ LOGGER.error(bRMSRawPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return bRMSRawPolicyService.getMessage();
+ }
+ // Get Result.
+ response = bRMSRawPolicyService.getResult(updateFlag);
+ break;
+ case Base:
+ ConfigPolicyService configPolicyService = new ConfigPolicyService(policyName, policyScope, policyParameters, date);
+ // Check Validation.
+ if(!configPolicyService.getValidation()){
+ LOGGER.error(configPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return configPolicyService.getMessage();
+ }
+ // Get Result.
+ response = configPolicyService.getResult(updateFlag);
+ break;
+ case ClosedLoop_Fault:
+ ClosedLoopFaultPolicyService closedLoopFaultPolicyService = new ClosedLoopFaultPolicyService(policyName, policyScope, policyParameters, date);
+ // Check Validation.
+ if(!closedLoopFaultPolicyService.getValidation()){
+ LOGGER.error(closedLoopFaultPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return closedLoopFaultPolicyService.getMessage();
+ }
+ // Get Result.
+ response = closedLoopFaultPolicyService.getResult(updateFlag);
+ break;
+ case ClosedLoop_PM:
+ ClosedLoopPMPolicyService closedLoopPMPolicyService = new ClosedLoopPMPolicyService(policyName, policyScope, policyParameters, date);
+ // Check Validation.
+ if(!closedLoopPMPolicyService.getValidation()){
+ LOGGER.error(closedLoopPMPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return closedLoopPMPolicyService.getMessage();
+ }
+ // Get Result.
+ response = closedLoopPMPolicyService.getResult(updateFlag);
+ break;
+ case Firewall:
+ FirewallPolicyService firewallPolicyService = new FirewallPolicyService(policyName, policyScope, policyParameters, date);
+ // Check Validation.
+ if(!firewallPolicyService.getValidation()){
+ LOGGER.error(firewallPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return firewallPolicyService.getMessage();
+ }
+ // Get Result.
+ response = firewallPolicyService.getResult(updateFlag);
+ break;
+ case MicroService:
+ MicroServicesPolicyService microServicesPolicyService = new MicroServicesPolicyService(policyName, policyScope, policyParameters, date);
+ // Check Validation.
+ if(!microServicesPolicyService.getValidation()){
+ LOGGER.error(microServicesPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return microServicesPolicyService.getMessage();
+ }
+ // Get Result.
+ response = microServicesPolicyService.getResult(updateFlag);
+ break;
+ default:
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " Invalid Config Type Present";
+ LOGGER.error(message);
+ status = HttpStatus.BAD_REQUEST;
+ return message;
+ }
+ }else if (policyParameters.getPolicyClass()!=null){
+ switch (policyParameters.getPolicyClass()){
+ case Action:
+ ActionPolicyService actionPolicyService = new ActionPolicyService(policyScope, policyName, policyParameters);
+ // Check Validation.
+ if(!actionPolicyService.getValidation()){
+ LOGGER.error(actionPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return actionPolicyService.getMessage();
+ }
+ // Get Result.
+ response = actionPolicyService.getResult(updateFlag);
+ break;
+ case Decision:
+ DecisionPolicyService decisionPolicyService = new DecisionPolicyService(policyScope, policyName, policyParameters);
+ // Check Validation.
+ if(!decisionPolicyService.getValidation()){
+ LOGGER.error(decisionPolicyService.getMessage());
+ status = HttpStatus.BAD_REQUEST;
+ return decisionPolicyService.getMessage();
+ }
+ // Get Result.
+ response = decisionPolicyService.getResult(updateFlag);
+ break;
+ }
+ }else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found.";
+ LOGGER.error(message);
+ status = HttpStatus.BAD_REQUEST;
+ response = message;
+ }
+ return response;
+ }
+
+ protected boolean getValidation() {
+ if(policyParameters == null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. ";
+ return false;
+ }
+ if(policyParameters.getPolicyName() == null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
+ return false;
+ }
+ if (policyParameters.getPolicyName().contains(".")) {
+ policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf(".") + 1,
+ policyParameters.getPolicyName().length());
+ policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf("."));
+ LOGGER.info("Name is " + policyName + " scope is " + policyScope);
+ } else {
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
+ return false;
+ }
+ if (policyName==null||policyName.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
+ return false;
+
+ }
+ message = PolicyUtils.emptyPolicyValidator(policyScope);
+ if(!message.contains("success")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
+ return false;
+ }
+ message = PolicyUtils.emptyPolicyValidator(policyName);
+ if(!message.contains("success")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
+ return false;
+ }
+ if(policyParameters.getPolicyDescription()!=null){
+ message = PolicyUtils.descriptionValidator(policyParameters.getPolicyDescription());
+ if(!message.contains("success")){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
+ return false;
+ }
+ }
+ if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.toString())){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "This requests contains Non ASCII Characters. Please review your input parameter"
+ + " values and correct the illegal characters.";
+ return false;
+ }
+ // Set some default Values.
+ if (policyParameters.getTtlDate()!=null){
+ date = convertDate(policyParameters.getTtlDate());
+ }
+ return true;
+ }
+
+ protected String convertDate(Date date) {
+ String strDate = null;
+ if (date!=null) {
+ SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
+ strDate = dateformatJava.format(date);
+ }
+ return (strDate==null) ? "NA": strDate;
+ }
+
+ protected void specialCheck() {
+ if(policyResult== null || policyResult.contains("BAD REQUEST")||policyResult.contains("PE300")){
+ status = HttpStatus.BAD_REQUEST;
+ } else if (policyResult.contains("Policy Exist Error")) {
+ status = HttpStatus.CONFLICT;
+ } else if (policyResult.contains("PE200")||policyResult.contains("PE900")){
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
+ }
+ }
+
+ public String getResult() {
+ return policyResult;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java
new file mode 100644
index 000000000..c6789a0b8
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java
@@ -0,0 +1,100 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.Map;
+
+import org.openecomp.policy.api.AttributeType;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.api.RuleProvider;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * Decision Policy Implementation
+ *
+ * @version 0.1
+ */
+public class DecisionPolicyService{
+ private static Logger LOGGER = FlexLogger.getLogger(DecisionPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private String message = null;
+ private String policyScope = null;
+ private String policyName = null;
+ private PolicyParameters policyParameters = null;
+ private String ecompName = null;
+
+ public DecisionPolicyService(String policyScope, String policyName,
+ PolicyParameters policyParameters) {
+ this.policyScope = policyScope;
+ this.policyName = policyName;
+ this.policyParameters = policyParameters;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ ecompName = policyParameters.getEcompName();
+ if (ecompName==null||ecompName.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.";
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException {
+ String response = null;
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ RuleProvider ruleProvider = policyParameters.getRuleProvider();
+ if (ruleProvider==null) {
+ ruleProvider = RuleProvider.CUSTOM ;
+ }
+ Map<String,String> matchingAttributes = null;
+ Map<String,String> settingsAttributes = null;
+ if (policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)) {
+ matchingAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING);
+ settingsAttributes = policyParameters.getAttributes().get(AttributeType.SETTINGS);
+ }else if(policyParameters.getAttributes()!=null && !policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
+ settingsAttributes = policyParameters.getAttributes().get(AttributeType.SETTINGS);
+ }else if(policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && !policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
+ matchingAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING);
+ }
+ // Create Policy.
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyParameters.getPolicyDescription(), ecompName, ruleProvider.toString(), matchingAttributes, settingsAttributes, policyParameters.getDynamicRuleAlgorithmLabels(),
+ policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmField2(), null, null, null, updateFlag, policyScope, 0);
+ // Send JSON to PAP.
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Decision"}, policyParameters.getRequestID(), "Decision");
+ LOGGER.info(message);
+ return response;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java
new file mode 100644
index 000000000..d0978fc5b
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java
@@ -0,0 +1,258 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.io.File;
+import java.util.UUID;
+
+import org.openecomp.policy.api.DeletePolicyParameters;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+import org.springframework.http.HttpStatus;
+
+public class DeletePolicyService {
+ private static Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName());
+
+ private String deleteResult = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private DeletePolicyParameters deletePolicyParameters = null;
+ private String message = null;
+ private String filePrefix = null;
+ private String clientScope = null;
+ private String policyType = null;
+ private String policyName = null;
+ private String policyScope = null;
+
+ public DeletePolicyService(DeletePolicyParameters deletePolicyParameters,
+ String requestID) {
+ this.deletePolicyParameters = deletePolicyParameters;
+ if(deletePolicyParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.deletePolicyParameters.setRequestID(requestUUID);
+ }
+ try{
+ run();
+ specialCheck();
+ }catch(PolicyException e){
+ deleteResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void specialCheck() {
+ if(deleteResult==null){
+ return;
+ }
+ if (deleteResult.contains("BAD REQUEST")||deleteResult.contains("PE300")||deleteResult.contains("not exist")||deleteResult.contains("Invalid policyName")) {
+ status = HttpStatus.BAD_REQUEST;
+ } else if (deleteResult.contains("locked down")){
+ status = HttpStatus.ACCEPTED;
+ } else if (deleteResult.contains("not Authorized")) {
+ status = HttpStatus.FORBIDDEN;
+ } else if (deleteResult.contains("groupId")) {
+ status = HttpStatus.NOT_FOUND;
+ } else if (deleteResult.contains("JPAUtils")||deleteResult.contains("database")||deleteResult.contains("policy file")||
+ deleteResult.contains("unknown")||deleteResult.contains("configuration")) {
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
+ }
+ }
+
+ private void run() throws PolicyException{
+ // Check Validation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ // Get Result.
+ try{
+ status = HttpStatus.OK;
+ deleteResult = processResult();
+ }catch (Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyException(e);
+ }
+ }
+
+ private String processResult() throws PolicyException{
+ String response = null;
+ String fullPolicyName = null;
+ String pdpGroup = deletePolicyParameters.getPdpGroup();
+ // PDP Group Check.
+ if (pdpGroup==null){
+ pdpGroup="NA";
+ }
+ PAPServices papServices = new PAPServices();
+ if (!deletePolicyParameters.getPolicyName().contains("xml")) {
+
+ String activeVersion = papServices.getActiveVersion(policyScope, filePrefix, policyName, clientScope, deletePolicyParameters.getRequestID());
+ LOGGER.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion);
+ String id = null;
+ if ("pe100".equalsIgnoreCase(activeVersion)) {
+ response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
+ + "Contact Administrator for this Scope. ";
+ LOGGER.error(response);
+ return response;
+ } else if ("pe300".equalsIgnoreCase(activeVersion)) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. "
+ + "This indicates a problem with getting the version from the PAP or the policy does not exist.";
+ LOGGER.error(response);
+ return response;
+ }
+ if (!activeVersion.equalsIgnoreCase("0")) {
+ id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml";
+ LOGGER.debug("The policyId is " + id);
+ } else {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. could not retrieve the activeVersion for this policy. "
+ + "This indicates the policy does not exist, please verify the policy exists.";
+ LOGGER.error(response);
+ return response;
+ }
+
+ fullPolicyName = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml";
+
+ } else {
+ fullPolicyName = policyName;
+ }
+
+ if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) {
+ if (deletePolicyParameters.getDeleteCondition()==null||deletePolicyParameters.getDeleteCondition().toString().trim().isEmpty()){
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given.";
+ LOGGER.error(message);
+ return message;
+ }
+
+ StdPAPPolicy deletePapPolicy = new StdPAPPolicy(fullPolicyName, deletePolicyParameters.getDeleteCondition().toString());
+ //send JSON object to PAP
+ response = (String) papServices.callPAP(deletePapPolicy, new String[] {"groupId="+pdpGroup, "apiflag=deletePapApi", "operation=delete" }, deletePolicyParameters.getRequestID(), clientScope);
+ } else if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) {
+ if (deletePolicyParameters.getPdpGroup()==null||deletePolicyParameters.getPdpGroup().trim().isEmpty()){
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given.";
+ LOGGER.error(message);
+ return message;
+ }
+ //send JSON object to PAP
+ response = (String) papServices.callPAP(null, new String[] {"policyName="+fullPolicyName, "groupId="+pdpGroup, "apiflag=deletePdpApi", "operation=delete" }, deletePolicyParameters.getRequestID(), clientScope);
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist. Please enter either PAP or PDP to delete the policy from a specified Policy Component.";
+ LOGGER.error(message);
+ response = message;
+ }
+ return response;
+ }
+
+ private boolean getValidation() {
+ // While Validating, extract the required values.
+ if (!deletePolicyParameters.getPolicyName().contains("xml")) {
+ if (deletePolicyParameters.getPolicyName() != null
+ && deletePolicyParameters.getPolicyName().contains(".")) {
+ policyName = deletePolicyParameters.getPolicyName().substring(deletePolicyParameters.getPolicyName().lastIndexOf(".") + 1,
+ deletePolicyParameters.getPolicyName().length());
+ policyScope = deletePolicyParameters.getPolicyName().substring(0,deletePolicyParameters.getPolicyName().lastIndexOf("."));
+ LOGGER.info("Name is " + policyName + " scope is " + policyScope);
+ } else {
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
+ return false;
+ }
+ } else {
+ policyName = deletePolicyParameters.getPolicyName();
+ }
+ if (deletePolicyParameters.getPolicyName()==null||deletePolicyParameters.getPolicyName().trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
+ return false;
+ }
+ policyType = deletePolicyParameters.getPolicyType();
+ if(policyType== null || policyType.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given.";
+ return false;
+ }
+ setClientScope();
+ if (clientScope==null||clientScope.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + deletePolicyParameters.getPolicyType() + " is not a valid Policy Type.";
+ LOGGER.error(message);
+ return false;
+ }
+ LOGGER.debug("clientScope is " + clientScope);
+ LOGGER.debug("filePrefix is " + filePrefix);
+ if(deletePolicyParameters.getPolicyComponent()==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given.";
+ return false;
+ }
+ return true;
+ }
+
+ private void setClientScope() {
+ if ("Firewall".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigFirewall";
+ filePrefix = "Config_FW_";
+ } else if ("Action".equalsIgnoreCase(policyType)) {
+ clientScope = "Action";
+ filePrefix = "Action_";
+ } else if ("Decision".equalsIgnoreCase(policyType)) {
+ clientScope = "Decision";
+ filePrefix = "Decision_";
+ } else if ("Base".equalsIgnoreCase(policyType)) {
+ clientScope = "Config";
+ filePrefix = "Config_";
+ } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigClosedLoop";
+ filePrefix = "Config_Fault_";
+ } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigClosedLoop";
+ filePrefix = "Config_PM_";
+ } else if ("MicroService".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigMS";
+ filePrefix = "Config_MS_";
+ }else if ("BRMS_RAW".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigBrmsRaw";
+ filePrefix = "Config_BRMS_Raw_";
+ } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigBrmsParam";
+ filePrefix = "Config_BRMS_Param_";
+ } else {
+ clientScope = null;
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType
+ + " is not a valid Policy Type.";
+ }
+ }
+
+ public String getResult() {
+ return deleteResult;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java
new file mode 100644
index 000000000..1d4305a3b
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java
@@ -0,0 +1,107 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import javax.json.JsonException;
+import javax.json.JsonObject;
+
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * Firewall Policy Implementation.
+ *
+ * @version 0.1
+ */
+public class FirewallPolicyService {
+ private static Logger LOGGER = FlexLogger.getLogger(FirewallPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private PolicyParameters policyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private String date = null;
+ private boolean levelCheck = false;
+ private JsonObject firewallJson = null;
+
+ public FirewallPolicyService(String policyName, String policyScope,
+ PolicyParameters policyParameters, String date) {
+ this.policyParameters = policyParameters;
+ this.policyName = policyName;
+ this.policyScope = policyScope;
+ this.date = date;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ if(policyParameters.getConfigBody()==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
+ return false;
+ }
+ try{
+ firewallJson = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody());
+ } catch(JsonException| IllegalStateException e){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
+ return false;
+ }
+ if(firewallJson==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config-Body given.";
+ return false;
+ }
+ levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel());
+ if (!levelCheck){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException {
+ String response = null;
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ //set values for basic policy information
+ String configName = firewallJson.get("configName").toString();
+ String configDescription = "";
+ String json = firewallJson.toString();
+ // Create Policy.
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Firewall Config", policyName, configDescription, configName, updateFlag, policyScope, json, 0,
+ policyParameters.getRiskLevel(),policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date);
+ // Send Json to PAP.
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigFirewall");
+ LOGGER.info(response);
+ return response;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java
new file mode 100644
index 000000000..b501a5c6a
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java
@@ -0,0 +1,303 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.json.Json;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+
+import org.openecomp.policy.api.ConfigRequestParameters;
+import org.openecomp.policy.api.PolicyConfigException;
+import org.openecomp.policy.api.PolicyConfigStatus;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.models.PDPResponse;
+import org.openecomp.policy.pdp.rest.api.models.PolicyConfig;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class GetConfigService {
+ private static Logger LOGGER = FlexLogger.getLogger(GetConfigService.class.getName());
+
+ private ConfigRequestParameters configRequestParameters = null;
+ private String message = null;
+ private HttpStatus responseCode = HttpStatus.BAD_REQUEST;
+ private Collection<PolicyConfig> policyConfigs = null;
+ private boolean unique = false;
+
+ public GetConfigService(ConfigRequestParameters configRequestParameters,
+ String requestID){
+ this.configRequestParameters = configRequestParameters;
+ if(configRequestParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.configRequestParameters.setRequestID(requestUUID);
+ }
+ policyConfigs = new ArrayList<PolicyConfig>();
+ try{
+ run();
+ specialCheck();
+ }catch(PolicyConfigException e){
+ PolicyConfig policyConfig = new PolicyConfig();
+ policyConfig.setPolicyConfigMessage(e.getMessage());
+ policyConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
+ policyConfigs.add(policyConfig);
+ responseCode = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void specialCheck() {
+ if(policyConfigs==null || policyConfigs.size()==0){
+ responseCode = HttpStatus.BAD_REQUEST;
+ }else if(policyConfigs.size()==1){
+ for(PolicyConfig policyConfig: policyConfigs){
+ if(policyConfig.getPolicyConfigMessage()!=null && policyConfig.getPolicyConfigMessage().contains("PE300")){
+ responseCode = HttpStatus.BAD_REQUEST;
+ }
+ }
+ }else{
+ responseCode = HttpStatus.OK;
+ }
+ }
+
+ private void run() throws PolicyConfigException{
+ // getValidation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyConfigException(message);
+ }
+ // Generate Request.
+ String modelString = getModel().toString();
+ LOGGER.debug("Generated JSON Request is: " + modelString);
+ if(configRequestParameters.getUnique()){
+ LOGGER.info("Requested for Unique Result only. ");
+ unique = true;
+ }
+ // Process Result.
+ try {
+ PDPServices pdpServices = new PDPServices();
+ responseCode = HttpStatus.OK;
+ policyConfigs = configResult(pdpServices.generateRequest(modelString, configRequestParameters.getRequestID(), unique, false));
+ // Filter addition.
+ policyConfigs = filterResults(policyConfigs, configRequestParameters);
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ responseCode = HttpStatus.BAD_REQUEST;
+ throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
+ }
+ }
+
+ private Collection<PolicyConfig> configResult(
+ Collection<PDPResponse> generateRequest) {
+ Collection<PolicyConfig> result = new HashSet<PolicyConfig>();
+ if (generateRequest == null) {
+ return null;
+ }
+ if (!generateRequest.isEmpty()) {
+ for (PDPResponse stdStatus : generateRequest) {
+ PolicyConfig policyConfig = new PolicyConfig();
+ policyConfig.setConfig(stdStatus.getConfig());
+ policyConfig.setMatchingConditions(stdStatus.getMatchingConditions());
+ policyConfig.setPolicyConfigMessage(stdStatus.getPolicyConfigMessage());
+ policyConfig.setPolicyConfigStatus(stdStatus.getPolicyConfigStatus());
+ policyConfig.setPolicyName(stdStatus.getPolicyName());
+ policyConfig.setPolicyVersion(stdStatus.getPolicyVersion());
+ policyConfig.setProperty(stdStatus.getProperty());
+ policyConfig.setResponseAttributes(stdStatus.getResponseAttributes());
+ policyConfig.setType(stdStatus.getType());
+ result.add(policyConfig);
+ }
+ }
+ return result;
+ }
+
+ // Filter logic required for results comparing with requests.
+ private Collection<PolicyConfig> filterResults(
+ Collection<PolicyConfig> policyConfigs,
+ ConfigRequestParameters configRequestParameters) {
+ List<PolicyConfig> policyConfig = new ArrayList<PolicyConfig>();
+ for(PolicyConfig config: policyConfigs){
+ if(config.getPolicyName()!=null && configRequestParameters.getPolicyName()!=null && configRequestParameters.getPolicyName().trim().length()>0){
+ if(!config.getPolicyName().matches(configRequestParameters.getPolicyName())){
+ continue;
+ }
+ }
+ if(config.getMatchingConditions()!=null && config.getMatchingConditions().size()>0){
+ if(configRequestParameters.getEcompName()!=null && configRequestParameters.getEcompName().trim().length()>0 && config.getMatchingConditions().containsKey("ECOMPName")){
+ if(!config.getMatchingConditions().get("ECOMPName").matches(configRequestParameters.getEcompName())){
+ continue;
+ }
+ }
+ if(configRequestParameters.getConfigName()!=null && configRequestParameters.getConfigName().trim().length()>0 && config.getMatchingConditions().containsKey("ConfigName")){
+ if(!config.getMatchingConditions().get("ConfigName").matches(configRequestParameters.getConfigName())){
+ continue;
+ }
+ }
+ if(configRequestParameters.getConfigAttributes()!=null && configRequestParameters.getConfigAttributes().size()>0){
+ boolean flag = false;
+ for(String key: configRequestParameters.getConfigAttributes().keySet()){
+ if(!config.getMatchingConditions().containsKey(key) || !config.getMatchingConditions().get(key).matches(configRequestParameters.getConfigAttributes().get(key))){
+ flag = true;
+ break;
+ }
+ }
+ if(flag){
+ continue;
+ }
+ }
+ }
+ policyConfig.add(config);
+ }
+ if(policyConfig.size()==0){
+ PolicyConfig pConfig = new PolicyConfig();
+ pConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
+ pConfig.setPolicyConfigMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+"No Match Found, for the parameters sent.");
+ policyConfig.add(pConfig);
+ }
+ return policyConfig;
+ }
+
+ private JsonObject getModel() throws PolicyConfigException{
+ String policyName = configRequestParameters.getPolicyName();
+ if(policyName!= null && !policyName.trim().isEmpty() && !policyName.endsWith("xml")){
+ policyName = policyName + ".[\\d].*";
+ configRequestParameters.setPolicyName(policyName);
+ }
+ JsonArrayBuilder subjectArray = Json.createArrayBuilder();
+ JsonArrayBuilder resourceArray = Json.createArrayBuilder();
+ if(configRequestParameters.getPolicyName()!=null){
+ JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
+ subjectBuilder.add("Value", policyName);
+ subjectBuilder.add("AttributeId", "PolicyName");
+ subjectArray.add(subjectBuilder);
+ }else{
+ LOGGER.info("PolicyName values are not given. ");
+ }
+ if(configRequestParameters.getEcompName()!=null){
+ JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
+ subjectBuilder.add("Value", configRequestParameters.getEcompName());
+ subjectBuilder.add("AttributeId", "ECOMPName");
+ subjectArray.add(subjectBuilder);
+ if(configRequestParameters.getConfigName()!=null){
+ subjectBuilder = Json.createObjectBuilder();
+ subjectBuilder.add("Value", configRequestParameters.getConfigName());
+ subjectBuilder.add("AttributeId", "ConfigName");
+ subjectArray.add(subjectBuilder);
+ resourceArray = getResourceArray(configRequestParameters.getConfigAttributes());
+ }else{
+ LOGGER.info("Config Name is not given. ");
+ }
+ }else{
+ LOGGER.info("Ecomp Name is not given. ");
+ }
+ JsonObject model = Json.createObjectBuilder()
+ .add("Request",Json.createObjectBuilder()
+ .add("AccessSubject",Json.createObjectBuilder()
+ .add("Attribute",subjectArray))
+ .add("Action",Json.createObjectBuilder()
+ .add("Attribute",Json.createObjectBuilder()
+ .add("Value","ACCESS")
+ .add("AttributeId","urn:oasis:names:tc:xacml:1.0:action:action-id")))
+ .add("Resource",Json.createObjectBuilder()
+ .add("Attribute",resourceArray
+ .add(Json.createObjectBuilder()
+ .add("Value","Config")
+ .add("AttributeId","urn:oasis:names:tc:xacml:1.0:resource:resource-id")))))
+ .build();
+ return model;
+ }
+
+ private JsonArrayBuilder getResourceArray(Map<String, String> configAttributes) throws PolicyConfigException{
+ JsonArrayBuilder resourceArray = Json.createArrayBuilder();
+ configAttributes = configRequestParameters.getConfigAttributes();
+ if (configAttributes != null && !configAttributes.isEmpty()) {
+ if(!configAttributes.containsKey("RiskType")){
+ configAttributes.put("RiskType", ".*");
+ }
+ if(!configAttributes.containsKey("RiskLevel")){
+ configAttributes.put("RiskLevel", ".*");
+ }
+ if(!configAttributes.containsKey("guard")){
+ configAttributes.put("guard", ".*");
+ }
+ if(!configAttributes.containsKey("TTLDate")){
+ configAttributes.put("TTLDate", ".*");
+ }
+ }else{
+ // ConfigAttributes is Null. So add basic values.
+ configAttributes = new HashMap<String,String>();
+ configAttributes.put("RiskType", ".*");
+ configAttributes.put("RiskLevel", ".*");
+ configAttributes.put("guard", ".*");
+ configAttributes.put("TTLDate", ".*");
+ }
+ for (String key : configAttributes.keySet()) {
+ if (key.isEmpty()) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key";
+ LOGGER.error(message);
+ throw new PolicyConfigException(message);
+ }
+ JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
+ resourceBuilder.add("Value", configAttributes.get(key));
+ resourceBuilder.add("AttributeId", key);
+ resourceArray.add(resourceBuilder);
+ }
+ return resourceArray;
+ }
+
+ private Boolean getValidation(){
+ if(configRequestParameters==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No config Request Parameters given.";
+ return false;
+ }
+ if(configRequestParameters.getEcompName()==null && configRequestParameters.getPolicyName()==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot proceed without eCOMPComponentName or PolicyName";
+ return false;
+ }
+ return true;
+ }
+
+ public Collection<PolicyConfig> getResult() {
+ return policyConfigs;
+ }
+
+ public HttpStatus getResponseCode() {
+ return responseCode;
+ }
+} \ No newline at end of file
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java
new file mode 100644
index 000000000..33f2d07d7
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java
@@ -0,0 +1,180 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.json.Json;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+
+import org.openecomp.policy.api.DecisionRequestParameters;
+import org.openecomp.policy.api.DecisionResponse;
+import org.openecomp.policy.api.PolicyDecision;
+import org.openecomp.policy.api.PolicyDecisionException;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.models.PDPResponse;
+import org.openecomp.policy.std.StdDecisionResponse;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class GetDecisionService {
+ private static Logger LOGGER = FlexLogger.getLogger(GetDecisionService.class.getName());
+
+ private DecisionResponse decisionResponse = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private DecisionRequestParameters decisionRequestParameters = null;
+ private String message = null;
+ private String eCOMPComponentName = null;
+ private Map<String,String> decisionAttributes = null;
+
+ public GetDecisionService(
+ DecisionRequestParameters decisionRequestParameters,
+ String requestID) {
+ this.decisionRequestParameters = decisionRequestParameters;
+ if(decisionRequestParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.decisionRequestParameters.setRequestID(requestUUID);
+ }
+ try{
+ run();
+ }catch(PolicyDecisionException e){
+ StdDecisionResponse decisionResponse = new StdDecisionResponse();
+ decisionResponse.setDecision(PolicyDecision.ERROR);
+ decisionResponse.setDetails(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ this.decisionResponse = decisionResponse;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void run() throws PolicyDecisionException{
+ // Get Validation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyDecisionException(message);
+ }
+ // Generate Request.
+ String modelString = getModel().toString();
+ LOGGER.debug("Generated JSON Request is: " + modelString);
+ // Process Result.
+ try {
+ PDPServices pdpServices = new PDPServices();
+ status = HttpStatus.OK;
+ decisionResponse = decisionResult(pdpServices.generateRequest(modelString, decisionRequestParameters.getRequestID(), false, true));
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyDecisionException(e);
+ }
+ }
+
+ private DecisionResponse decisionResult(
+ Collection<PDPResponse> generateRequest) {
+ StdDecisionResponse policyDecision = new StdDecisionResponse();
+ if (generateRequest == null) {
+ return policyDecision;
+ }
+ if (!generateRequest.isEmpty()) {
+ for (PDPResponse stdStatus : generateRequest) {
+ policyDecision.setDecision(stdStatus.getDecision());
+ policyDecision.setDetails(stdStatus.getDetails());
+ }
+ }
+ return policyDecision;
+ }
+
+ private JsonObject getModel() throws PolicyDecisionException{
+ JsonArrayBuilder resourceArray = Json.createArrayBuilder();
+ for (String key : decisionAttributes.keySet()) {
+ if (key.isEmpty()) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key";
+ LOGGER.error(message);
+ throw new PolicyDecisionException(message);
+ }
+ JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
+ if (decisionAttributes.get(key).matches("[0-9]+")) {
+ int val = Integer.parseInt(decisionAttributes.get(key));
+ resourceBuilder.add("Value", val);
+ } else {
+ resourceBuilder.add("Value", decisionAttributes.get(key));
+ }
+ resourceBuilder.add("AttributeId", key);
+ resourceArray.add(resourceBuilder);
+ }
+ JsonObject model = Json
+ .createObjectBuilder()
+ .add("Request", Json.createObjectBuilder()
+ .add("AccessSubject", Json.createObjectBuilder()
+ .add("Attribute", Json.createObjectBuilder()
+ .add("Value", eCOMPComponentName)
+ .add("AttributeId", "ECOMPName")))
+ .add("Resource", Json.createObjectBuilder()
+ .add("Attribute", resourceArray))
+ .add("Action", Json.createObjectBuilder()
+ .add("Attribute", Json.createObjectBuilder()
+ .add("Value", "DECIDE")
+ .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id"))))
+ .build();
+ return model;
+ }
+
+ private boolean getValidation() {
+ if(decisionRequestParameters==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Paramaters";
+ return false;
+ }
+ eCOMPComponentName = decisionRequestParameters.getECOMPComponentName();
+ decisionAttributes = decisionRequestParameters.getDecisionAttributes();
+ if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName;
+ return false;
+ }
+ if (decisionAttributes == null && decisionAttributes.isEmpty()) {
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Attributes Given. ";
+ return false;
+ }
+ return true;
+ }
+
+ public DecisionResponse getResult() {
+ return decisionResponse;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
+
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java
new file mode 100644
index 000000000..2305ecbec
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java
@@ -0,0 +1,273 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.UUID;
+
+import javax.json.JsonException;
+import javax.json.JsonObject;
+
+import org.openecomp.policy.api.DictionaryParameters;
+import org.openecomp.policy.api.DictionaryResponse;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.std.StdDictionaryResponse;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class GetDictionaryService {
+ private static Logger LOGGER = FlexLogger.getLogger(GetDictionaryService.class.getName());
+
+ private DictionaryResponse dictionaryResponse = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private String message = null;
+ private DictionaryParameters dictionaryParameters = null;
+
+ public GetDictionaryService(DictionaryParameters dictionaryParameters,
+ String requestID) {
+ this.dictionaryParameters = dictionaryParameters;
+ if(dictionaryParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.dictionaryParameters.setRequestID(requestUUID);
+ }
+ try{
+ run();
+ specialCheck();
+ }catch(PolicyException e){
+ StdDictionaryResponse dictionaryResponse = new StdDictionaryResponse();
+ dictionaryResponse.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ this.dictionaryResponse = dictionaryResponse;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void specialCheck() {
+ if(dictionaryResponse!=null){
+ if(dictionaryResponse.getResponseMessage()!=null && dictionaryResponse.getResponseMessage().contains("PE300")){
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+ }
+
+ private void run() throws PolicyException{
+ // Check Validation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ // Get Result.
+ try{
+ status = HttpStatus.OK;
+ dictionaryResponse = processResult();
+ }catch (Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyException(e);
+ }
+ }
+
+ private DictionaryResponse processResult() throws PolicyException{
+ StdDictionaryResponse response = new StdDictionaryResponse();
+ PAPServices papServices = new PAPServices();
+ String result = (String) papServices.callPAP(null, new String[] {"operation=get", "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem");
+
+ if (result!=null && result.contains("data")) {
+ String jsonString = formatDictionaryJson(result);
+ String responseMessage = result.substring(0, 82);
+ JsonObject json = null;
+ try{
+ json = PolicyApiUtils.stringToJsonObject(jsonString.replace("\\\\\\", "\\"));
+ String datas = json.getString("data").replaceFirst("\"\\[", "[");
+ int i = datas.lastIndexOf("]");
+ if( i>=0 ) {
+ datas = new StringBuilder(datas).replace(i, i+2,"]").toString();
+ }
+ json = PolicyApiUtils.stringToJsonObject(datas);
+ } catch(JsonException| IllegalStateException e){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson();
+ LOGGER.error(message);
+ response.setResponseMessage(message);
+ response.setResponseCode(400);
+ return response;
+ }
+ response.setResponseCode(papServices.getResponseCode());
+ response.setDictionaryJson(json);
+ response.setResponseMessage(responseMessage);
+ } else {
+ response.setResponseCode(400);
+ response.setResponseMessage(result);
+ }
+ return response;
+ }
+
+ private String formatDictionaryJson(String result) {
+ String jsonString = result.substring(82);
+ String dictionary = dictionaryParameters.getDictionary();
+
+ switch (dictionary) {
+ case "EcompName":
+ jsonString = jsonString.replace("ecompNameDictionaryDatas", "DictionaryDatas");
+ break;
+ case "Attribute":
+ jsonString = jsonString.replace("attributeDictionaryDatas", "DictionaryDatas");
+ break;
+ case "Action":
+ jsonString = jsonString.replace("actionPolicyDictionaryDatas", "DictionaryDatas");
+ break;
+ case "BRMSParamTemplate":
+ jsonString = jsonString.replace("brmsParamDictionaryDatas", "DictionaryDatas");
+ break;
+ case "VSCLAction":
+ jsonString = jsonString.replace("vsclActionDictionaryDatas", "DictionaryDatas");
+ break;
+ case "VNFType":
+ jsonString = jsonString.replace("vnfTypeDictionaryDatas", "DictionaryDatas");
+ break;
+ case "PEPOptions":
+ jsonString = jsonString.replace("pepOptionsDictionaryDatas", "DictionaryDatas");
+ break;
+ case "Varbind":
+ jsonString = jsonString.replace("varbindDictionaryDatas", "DictionaryDatas");
+ break;
+ case "Service":
+ jsonString = jsonString.replace("closedLoopServiceDictionaryDatas", "DictionaryDatas");
+ break;
+ case "Site":
+ jsonString = jsonString.replace("closedLoopSiteDictionaryDatas", "DictionaryDatas");
+ break;
+ case "Settings":
+ jsonString = jsonString.replace("settingsDictionaryDatas", "DictionaryDatas");
+ break;
+ case "DescriptiveScope":
+ jsonString = jsonString.replace("descriptiveScopeDictionaryDatas", "DictionaryDatas");
+ break;
+ case "Enforcer":
+ jsonString = jsonString.replace("enforcerDictionaryDatas", "DictionaryDatas");
+ break;
+ case "ActionList":
+ jsonString = jsonString.replace("actionListDictionaryDatas", "DictionaryDatas");
+ break;
+ case "ProtocolList":
+ jsonString = jsonString.replace("protocolListDictionaryDatas", "DictionaryDatas");
+ break;
+ case "Zone":
+ jsonString = jsonString.replace("zoneDictionaryDatas", "DictionaryDatas");
+ break;
+ case "SecurityZone":
+ jsonString = jsonString.replace("securityZoneDictionaryDatas", "DictionaryDatas");
+ break;
+ case "PrefixList":
+ jsonString = jsonString.replace("prefixListDictionaryDatas", "DictionaryDatas");
+ break;
+ case "AddressGroup":
+ jsonString = jsonString.replace("addressGroupDictionaryDatas", "DictionaryDatas");
+ break;
+ case "ServiceGroup":
+ jsonString = jsonString.replace("serviceGroupDictionaryDatas", "DictionaryDatas");
+ break;
+ case "ServiceList":
+ jsonString = jsonString.replace("serviceListDictionaryDatas", "DictionaryDatas");
+ break;
+ case "TermList":
+ case "RuleList":
+ case "FirewallRuleList":
+ case "Term":
+ jsonString = jsonString.replace("termListDictionaryDatas", "DictionaryDatas");
+ break;
+ case "MicroServiceLocation":
+ jsonString = jsonString.replace("microServiceLocationDictionaryDatas", "DictionaryDatas");
+ break;
+ case "MicroServiceConfigName":
+ jsonString = jsonString.replace("microServiceCongigNameDictionaryDatas", "DictionaryDatas");
+ break;
+ case "DCAEUUID":
+ jsonString = jsonString.replace("dcaeUUIDDictionaryDatas", "DictionaryDatas");
+ break;
+ case "MicroServiceModels":
+ jsonString = jsonString.replace("microServiceModelsDictionaryDatas", "DictionaryDatas");
+ break;
+ case "PolicyScopeService":
+ jsonString = jsonString.replace("psServiceDictionaryDatas", "DictionaryDatas");
+ break;
+ case "PolicyScopeResource":
+ jsonString = jsonString.replace("psResourceDictionaryDatas", "DictionaryDatas");
+ break;
+ case "PolicyScopeType":
+ jsonString = jsonString.replace("psTypeDictionaryDatas", "DictionaryDatas");
+ break;
+ case "PolicyScopeClosedLoop":
+ jsonString = jsonString.replace("psClosedLoopDictionaryDatas", "DictionaryDatas");
+ break;
+ case "GroupPolicyScopeList":
+ jsonString = jsonString.replace("groupPolicyScopeListDatas", "DictionaryDatas");
+ break;
+ case "RiskType":
+ jsonString = jsonString.replace("riskTypeDictionaryDatas", "DictionaryDatas");
+ break;
+ case "SafePolicyWarning":
+ jsonString = jsonString.replace("safePolicyWarningDatas", "DictionaryDatas");
+ break;
+ case "MicroServiceDictionary":
+ jsonString = jsonString.replace("microServiceDictionaryDatas", "DictionaryDatas");
+ break;
+ default:
+ return null;
+ }
+ return jsonString;
+ }
+
+ private boolean getValidation() {
+ if(dictionaryParameters==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Dictionary Parameters are not given.";
+ return false;
+ }
+ if(dictionaryParameters.getDictionaryType()==null || dictionaryParameters.getDictionaryType().toString().trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given.";
+ return false;
+ }
+ if(dictionaryParameters.getDictionary()==null || dictionaryParameters.getDictionary().trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given.";
+ return false;
+ }
+ return true;
+ }
+
+ public DictionaryResponse getResult() {
+ return dictionaryResponse;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java
new file mode 100644
index 000000000..14812edfb
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java
@@ -0,0 +1,160 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.UUID;
+
+import javax.json.JsonException;
+
+import org.json.JSONObject;
+import org.openecomp.policy.api.MetricsRequestParameters;
+import org.openecomp.policy.api.MetricsResponse;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.std.StdMetricsResponse;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class GetMetricsService {
+ private static Logger LOGGER = FlexLogger
+ .getLogger(GetDictionaryService.class.getName());
+
+ private MetricsResponse response = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private String message = null;
+ private MetricsRequestParameters metricsParameters = null;
+
+ public GetMetricsService(String requestID) {
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ } else {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ metricsParameters = new MetricsRequestParameters();
+ this.metricsParameters.setRequestID(requestUUID);
+
+ try {
+ run();
+ specialCheck();
+ } catch (PolicyException e) {
+ StdMetricsResponse metricsResponse = new StdMetricsResponse();
+ metricsResponse
+ .setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + e);
+ this.response = metricsResponse;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void specialCheck() {
+ if (response != null) {
+ if (response.getResponseMessage() != null
+ && response.getResponseMessage().contains("PE300")) {
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+ }
+
+ private void run() throws PolicyException {
+ // Check Validation.
+ /*
+ * if(!getValidation()){ LOGGER.error(message); throw new
+ * PolicyException(message); }
+ */
+ // Get Result.
+ try {
+ status = HttpStatus.OK;
+ response = processResult();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyException(e);
+ }
+ }
+
+ private MetricsResponse processResult() throws PolicyException {
+ StdMetricsResponse metricsResponse = new StdMetricsResponse();
+ PAPServices papServices = new PAPServices();
+ String result = (String) papServices.callPAP(null, new String[] {
+ "operation=get", "apiflag=getMetrics" },
+ metricsParameters.getRequestID(), "metrics");
+
+ JSONObject json = null;
+ if (result != null) {
+ if (result.length() > 81 && result.contains("{")) {
+ try {
+ String responseMessage = result.substring(0, 82);
+ String jsonString = result.substring(result.indexOf("{"),
+ result.length());
+ json = new JSONObject(jsonString);
+
+ int papCount = (int) json.get("papCount");
+ int pdpCount = (int) json.get("pdpCount");
+
+ metricsResponse.setResponseCode(papServices
+ .getResponseCode());
+ metricsResponse.setResponseMessage(responseMessage);
+ metricsResponse.setPapMetrics(papCount);
+ metricsResponse.setPdpMetrics(pdpCount);
+
+ } catch (JsonException | IllegalStateException e) {
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + " improper JSON object : " + json.toString();
+ LOGGER.error(message);
+ metricsResponse.setResponseMessage(message);
+ metricsResponse.setResponseCode(400);
+ return metricsResponse;
+ }
+ } else {
+ message = result;
+ metricsResponse.setResponseCode(400);
+ metricsResponse.setResponseMessage(message);
+ return metricsResponse;
+ }
+
+ } else {
+ message = XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "There was an issue with connecting to the PAP, "
+ + "review the logs for further debugging.";
+ metricsResponse.setResponseCode(500);
+ metricsResponse.setResponseMessage(message);
+ return metricsResponse;
+ }
+
+ return metricsResponse;
+ }
+
+ public MetricsResponse getResult() {
+ return response;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java
new file mode 100644
index 000000000..9aca4c049
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.openecomp.policy.api.ConfigRequestParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.models.PolicyConfig;
+import org.springframework.http.HttpStatus;
+
+public class ListConfigService {
+ private static Logger LOGGER = FlexLogger.getLogger(ListConfigService.class.getName());
+
+ private Collection<String> results = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+
+ public ListConfigService(ConfigRequestParameters configRequestParameters,
+ String requestID) {
+ GetConfigService getConfigService = new GetConfigService(configRequestParameters,requestID);
+ Collection<PolicyConfig> policyConfigs = getConfigService.getResult();
+ LOGGER.info("Transferring Config Results to List. ");
+ if(policyConfigs!=null){
+ results = new ArrayList<String>();
+ status = HttpStatus.OK;
+ for(PolicyConfig policyConfig : policyConfigs){
+ if(policyConfig.getPolicyConfigMessage()!=null && policyConfig.getPolicyConfigMessage().contains("PE300")){
+ results.add(policyConfig.getPolicyConfigMessage());
+ status = HttpStatus.BAD_REQUEST;
+ } else {
+ results.add("Policy Name: " + policyConfig.getPolicyName());
+ }
+ }
+ }
+ }
+
+ public Collection<String> getResult() {
+ return results;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java
new file mode 100644
index 000000000..636b7fbf8
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java
@@ -0,0 +1,123 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import javax.json.JsonException;
+import javax.json.JsonObject;
+
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+
+/**
+ * MicroServices Policy implementation.
+ *
+ * @version 0.1
+ */
+public class MicroServicesPolicyService{
+ private static Logger LOGGER = FlexLogger.getLogger(MicroServicesPolicyService.class.getName());
+ private static PAPServices papServices = null;
+
+ private PolicyParameters policyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private String date = null;
+ private String ecompName = null;
+ private JsonObject microServiceAttributes = null;
+ private boolean levelCheck = false;
+
+ public MicroServicesPolicyService(String policyName, String policyScope, PolicyParameters policyParameters, String date) {
+ this.policyParameters = policyParameters;
+ this.policyName = policyName;
+ this.policyScope = policyScope;
+ this.date = date;
+ papServices = new PAPServices();
+ }
+
+ public Boolean getValidation() {
+ if(policyParameters.getConfigBody()==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Micro Service or Attributes Config Body Present";
+ return false;
+ }
+ try{
+ microServiceAttributes = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody());
+ } catch(JsonException| IllegalStateException e){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
+ return false;
+ }
+ ecompName = policyParameters.getEcompName();
+ if (ecompName==null||ecompName.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
+ return false;
+ }
+ levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel());
+ if (!levelCheck){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
+ return false;
+ }
+ return true;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getResult(boolean updateFlag) throws PolicyException{
+ String response = null;
+ String operation = null;
+ if (updateFlag){
+ operation = "update";
+ } else {
+ operation = "create";
+ }
+ // get values and attributes from the JsonObject
+ String uuid = null;
+ String msLocation = null;
+ String configName = null;
+ String microService = microServiceAttributes.get("service").toString().replace("\"", "");
+ if (microServiceAttributes.get("uuid")!=null){
+ uuid = microServiceAttributes.get("uuid").toString().replace("\"", "");
+ }
+ if (microServiceAttributes.get("location")!=null){
+ msLocation = microServiceAttributes.get("location").toString().replace("\"", "");
+ }
+ if (microServiceAttributes.get("configName")!=null){
+ configName = microServiceAttributes.get("configName").toString().replace("\"", "");
+ }
+ String policyDescription = microServiceAttributes.get("description").toString().replace("\"", "");
+ String priority = microServiceAttributes.get("priority").toString().replace("\"", "");
+ String version = microServiceAttributes.get("version").toString().replace("\"", "");
+
+ // Create Policy.
+ StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Micro Service", policyName, policyDescription, ecompName,
+ configName, microService, uuid, msLocation, microServiceAttributes.toString(), priority,
+ version, updateFlag, policyScope, 0, policyParameters.getRiskLevel(),
+ policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date);
+ // Send JSON Object to PAP.
+ response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigMS");
+ LOGGER.info("Policy MS created Response: " + response);
+ return response;
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java
new file mode 100644
index 000000000..b00346de6
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java
@@ -0,0 +1,900 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.apache.commons.io.IOUtils;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.config.PDPApiAuth;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
+
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class PAPServices {
+ private static final String SUCCESS = "success";
+ private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class
+ .getName());
+
+ private int responseCode = 0;
+ private static String environment = "DEVL";
+ private static Boolean junit = false;
+ private static List<String> paps = null;
+ private static final Object papResourceLock = new Object();
+ private String operation = null;
+ private String requestMethod = null;
+ private String encoding = null;
+
+ public PAPServices() {
+ environment = PDPApiAuth.getEnvironment();
+ if(paps == null){
+ synchronized (papResourceLock) {
+ String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS);
+ if(urlList == null){
+ urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ }
+ paps = Arrays.asList(urlList.split(","));
+ }
+ }
+ }
+
+ private String getPAPEncoding(){
+ if(encoding == null){
+ String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
+ String pass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
+ Base64.Encoder encoder = Base64.getEncoder();
+ encoding = encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8));
+ }
+ return encoding;
+ }
+
+ private void rotatePAPList(){
+ synchronized (papResourceLock) {
+ Collections.rotate(paps, -1);
+ }
+ }
+
+ private String getPAP(){
+ String result;
+ synchronized (papResourceLock) {
+ result = paps.get(0);
+ }
+ return result;
+ }
+
+ public int getResponseCode() {
+ return responseCode;
+ }
+
+ public Object callPAP(Object content, String[] parameters, UUID requestID,
+ String clientScope) throws PolicyException {
+ String response = null;
+ HttpURLConnection connection = null;
+ responseCode = 0;
+ // Checking for the available PAPs is done during the first Request and
+ // the List is going to have the connected PAP as first element.
+ // This makes it Real-Time to change the list depending on their
+ // availability.
+ if (paps == null || paps.isEmpty()) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.";
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ int papsCount = 0;
+ boolean connected = false;
+ while (papsCount < paps.size()) {
+ try {
+ String fullURL = getPAP();
+ fullURL = checkParameter(parameters, fullURL);
+ URL url = new URL(fullURL);
+ LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---");
+ // Open the connection
+ connection = (HttpURLConnection) url.openConnection();
+ // Setting Content-Type
+ connection.setRequestProperty("Content-Type","application/json");
+ // Adding Authorization
+ connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding());
+ connection.setRequestProperty("Environment", environment);
+ connection.setRequestProperty("ClientScope", clientScope);
+ // set the method and headers
+ connection.setRequestMethod(requestMethod);
+ connection.setUseCaches(false);
+ connection.setInstanceFollowRedirects(false);
+ connection.setDoOutput(true);
+ connection.setDoInput(true);
+ // Adding RequestID
+ if (requestID == null) {
+ requestID = UUID.randomUUID();
+ LOGGER.info("No request ID provided, sending generated ID: "
+ + requestID.toString());
+ } else {
+ LOGGER.info("Using provided request ID: "
+ + requestID.toString());
+ }
+ connection.setRequestProperty("X-ECOMP-RequestID",
+ requestID.toString());
+ if (content != null && (content instanceof InputStream)) {
+ // send current configuration
+ try (OutputStream os = connection.getOutputStream()) {
+ int count = IOUtils.copy((InputStream) content, os);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("copied to output, bytes=" + count);
+ }
+ }
+ } else if(content != null){
+ // the content is an object to be encoded in JSON
+ ObjectMapper mapper = new ObjectMapper();
+ if (!junit) {
+ mapper.writeValue(connection.getOutputStream(),
+ content);
+ }
+ }
+ // DO the connect
+ connection.connect();
+ responseCode = connection.getResponseCode();
+ // If Connected to PAP then break from the loop and continue
+ // with the Request
+ if (connection.getResponseCode() > 0 || junit) {
+ connected = true;
+ break;
+ } else {
+ LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode());
+ rotatePAPList();
+ }
+ } catch (Exception e) {
+ // This means that the PAP is not working
+ if (junit) {
+ connected = true;
+ break;
+ }
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "PAP connection Error : " + e);
+ rotatePAPList();
+ }
+ papsCount++;
+ }
+ if (connected) {
+ // Read the Response
+ LOGGER.debug("connected to the PAP : " + getPAP());
+ LOGGER.debug("--- Response: ---");
+ Map<String, List<String>> headers = connection.getHeaderFields();
+ for (String key : headers.keySet()) {
+ LOGGER.debug("Header :" + key + " Value: " + headers.get(key));
+ }
+
+ try {
+ response = checkResponse(connection, requestID);
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e;
+ throw new PolicyException(
+ XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "Decoding the result ", e);
+ }
+ if (junit) {
+ response = SUCCESS;
+ }
+ return response;
+ } else {
+ response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "Unable to get valid response from PAP(s) " + paps;
+ return response;
+ }
+ }
+
+ public String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) {
+ String version = null;
+ HttpURLConnection connection = null;
+ String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName};
+ if (paps == null || paps.isEmpty()) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }else {
+ int papsCount = 0;
+ boolean connected = false;
+ while (papsCount < paps.size()) {
+ try {
+ String fullURL = getPAP();
+ if (parameters != null && parameters.length > 0) {
+ String queryString = "";
+ for (String p : parameters) {
+ queryString += "&" + p;
+ }
+ fullURL += "?" + queryString.substring(1);
+ }
+
+ URL url = new URL (fullURL);
+
+ //Open the connection
+ connection = (HttpURLConnection)url.openConnection();
+
+ // Setting Content-Type
+ connection.setRequestProperty("Content-Type",
+ "application/json");
+
+ // Adding Authorization
+ connection.setRequestProperty("Authorization", "Basic "
+ + getPAPEncoding());
+
+ connection.setRequestProperty("Environment", environment);
+ connection.setRequestProperty("ClientScope", clientScope);
+
+
+ //set the method and headers
+ connection.setRequestMethod("GET");
+ connection.setUseCaches(false);
+ connection.setInstanceFollowRedirects(false);
+ connection.setDoOutput(true);
+ connection.setDoInput(true);
+ // mb1915 - begin
+ // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
+ connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
+ // mb1915 - end
+
+ //DO the connect
+ connection.connect();
+
+ // If Connected to PAP then break from the loop and continue with the Request
+ if (connection.getResponseCode() > 0) {
+ connected = true;
+ break;
+
+ } else {
+ LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
+ }
+ } catch (Exception e) {
+ // This means that the PAP is not working
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
+ rotatePAPList();
+ }
+ papsCount++;
+ }
+
+ if (connected) {
+ //Read the Response
+ LOGGER.debug("connected to the PAP : " + getPAP());
+ LOGGER.debug("--- Response: ---");
+ Map<String, List<String>> headers = connection.getHeaderFields();
+ for (String key : headers.keySet()) {
+ LOGGER.debug("Header :" + key + " Value: " + headers.get(key));
+ }
+ try {
+ if (connection.getResponseCode() == 200) {
+ // Check for successful creation of policy
+ version = connection.getHeaderField("version");
+ LOGGER.debug("ActiveVersion from the Header: " + version);
+ } else if (connection.getResponseCode() == 403) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is "
+ + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ");
+ version = "pe100";
+ } else if (connection.getResponseCode() == 404) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is "
+ + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP");
+ version = "pe300";
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect.");
+ }
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
+ } catch (Exception e1) {
+ LOGGER.error(e1.getMessage());
+ }
+ }
+
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+ }
+ return version;
+ }
+
+ public StdPDPPolicy getGitPath(String policyScope, String filePrefix, String policyName, String activeVersion, String clientScope, UUID requestID, String id) throws PolicyException{
+ String gitPath = null;
+ Boolean isValid = false;
+ String policyId= null;
+ String description = null;
+ String pushVersion = null;
+ HttpURLConnection connection = null;
+ String [] parameters = {"apiflag=gitPath", "policyScope="+policyScope, "filePrefix="+filePrefix,
+ "policyName="+policyName, "activeVersion="+activeVersion};
+ if (paps == null || paps.isEmpty()) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }else {
+ int papsCount = 0;
+ boolean connected = false;
+ while (papsCount < paps.size()) {
+ try {
+ String fullURL = getPAP();
+ if (parameters != null && parameters.length > 0) {
+ String queryString = "";
+ for (String p : parameters) {
+ queryString += "&" + p;
+ }
+ fullURL += "?" + queryString.substring(1);
+ }
+
+ URL url = new URL (fullURL);
+
+ //Open the connection
+ connection = (HttpURLConnection)url.openConnection();
+
+ // Setting Content-Type
+ connection.setRequestProperty("Content-Type",
+ "application/json");
+
+ // Adding Authorization
+ connection.setRequestProperty("Authorization", "Basic "
+ +getPAPEncoding());
+
+ connection.setRequestProperty("Environment", environment);
+ connection.setRequestProperty("ClientScope", clientScope);
+
+ //set the method and headers
+ connection.setRequestMethod("GET");
+ connection.setUseCaches(false);
+ connection.setInstanceFollowRedirects(false);
+ connection.setDoOutput(true);
+ connection.setDoInput(true);
+ // mb1915 - begin
+ // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
+ connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
+ // mb1915 - end
+
+ //DO the connect
+ connection.connect();
+
+ // If Connected to PAP then break from the loop and continue with the Request
+ if (connection.getResponseCode() > 0) {
+ connected = true;
+ break;
+
+ } else {
+ LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
+ }
+ } catch (Exception e) {
+ // This means that the PAP is not working
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
+ rotatePAPList();
+ }
+ papsCount++;
+ }
+
+ if (connected) {
+ //Read the Response
+ LOGGER.debug("connected to the PAP : " + getPAP());
+ LOGGER.debug("--- Response: ---");
+ Map<String, List<String>> headers = connection.getHeaderFields();
+ for (String key : headers.keySet()) {
+ LOGGER.debug("Header :" + key + " Value: " + headers.get(key));
+ }
+ try {
+ if (connection.getResponseCode() == 200) {
+ // Check for successful creation of policy
+ gitPath = connection.getHeaderField("gitPath");
+ policyId = connection.getHeaderField("policyId");
+ description = connection.getHeaderField("description");
+ pushVersion = connection.getHeaderField("version");
+ isValid = Boolean.parseBoolean(connection.getHeaderField("isValid"));
+
+ LOGGER.debug("GitPath from Header: " + gitPath);
+ LOGGER.debug("policyId from Header: " + policyId);
+ LOGGER.debug("description from Header: " + description);
+ LOGGER.debug("version from Header: " + pushVersion);
+ LOGGER.debug("isValid from Header: " + isValid);
+
+ /*if (gitPath != null && !gitPath.equalsIgnoreCase("")) {
+ return gitPath;
+ }*/ if (gitPath == null || gitPath.trim().isEmpty()) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
+ }
+ } else if (connection.getResponseCode() == 404) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is "
+ + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP");
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST: Error occured while getting the gitPath from the PAP. The request may be incorrect.");
+ }
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
+ } catch (Exception e1) {
+ LOGGER.error(e1.getMessage());
+ }
+ }
+
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+ }
+ LOGGER.debug("Full gitPath policy xml file: " + gitPath);
+ URI selectedURI = getSelectedURI(gitPath, clientScope, requestID);
+ LOGGER.debug("The selectedURI is : " + selectedURI.toString());
+ String name = filePrefix+policyName;
+
+ StdPDPPolicy selectedPolicy;
+ try {
+ selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI, isValid, policyId, description, pushVersion);
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+e.getMessage());
+ throw new PolicyException(e);
+ }
+ return selectedPolicy;
+ }
+
+ private URI getSelectedURI(String gitPath, String clientScope, UUID requestID){
+ URI selectedURI = null;
+ HttpURLConnection connection = null;
+ String [] parameters = {"apiflag=uri", "gitPath="+gitPath};
+ if (paps == null || paps.isEmpty()) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }else {
+ int papsCount = 0;
+ boolean connected = false;
+ while (papsCount < paps.size()) {
+ try {
+ String fullURL = getPAP();
+ if (parameters != null && parameters.length > 0) {
+ String queryString = "";
+ for (String p : parameters) {
+ queryString += "&" + p;
+ }
+ fullURL += "?" + queryString.substring(1);
+ }
+
+ URL url = new URL (fullURL);
+
+ //Open the connection
+ connection = (HttpURLConnection)url.openConnection();
+
+ // Setting Content-Type
+ connection.setRequestProperty("Content-Type",
+ "application/json");
+
+ // Adding Authorization
+ connection.setRequestProperty("Authorization", "Basic "
+ + getPAPEncoding());
+
+ connection.setRequestProperty("Environment", environment);
+ connection.setRequestProperty("ClientScope", clientScope);
+
+ //set the method and headers
+ connection.setRequestMethod("GET");
+ connection.setUseCaches(false);
+ connection.setInstanceFollowRedirects(false);
+ connection.setDoOutput(true);
+ connection.setDoInput(true);
+ // mb1915 - begin
+ // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
+ connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
+ // mb1915 - end
+
+ //DO the connect
+ connection.connect();
+ responseCode = connection.getResponseCode();
+ // If Connected to PAP then break from the loop and continue with the Request
+ if (connection.getResponseCode() > 0) {
+ connected = true;
+ break;
+
+ } else {
+ LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
+ }
+ } catch (Exception e) {
+ // This means that the PAP is not working
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
+ rotatePAPList();
+ }
+ papsCount++;
+ }
+
+ if (connected) {
+ //Read the Response
+ LOGGER.debug("connected to the PAP : " + getPAP());
+ LOGGER.debug("--- Response: ---");
+ Map<String, List<String>> headers = connection.getHeaderFields();
+ for (String key : headers.keySet()) {
+ LOGGER.debug("Header :" + key + " Value: " + headers.get(key));
+ }
+ try {
+ if (connection.getResponseCode() == 200) {
+ // Check for successful creation of policy
+ String uri = connection.getHeaderField("selectedURI");
+ LOGGER.debug("URI from Header: " + uri);
+ if (uri != null && !uri.equalsIgnoreCase("")) {
+ selectedURI = URI.create(uri);
+ return selectedURI;
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
+ }
+ } else if (connection.getResponseCode() == 404) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is "
+ + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP");
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST: Error occured while getting the gitPath from the PAP. The request may be incorrect.");
+ }
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
+ } catch (Exception e1) {
+ LOGGER.error(e1.getMessage());
+ }
+ }
+
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
+ try {
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+ }
+ return selectedURI;
+ }
+
+ private String checkResponse(HttpURLConnection connection, UUID requestID) throws IOException {
+ String response = null;
+ if (responseCode == 200 || junit) {
+ // Check for successful creation of policy
+ String isSuccess = null;
+ if (!junit) { // is this a junit test?
+ isSuccess = connection.getHeaderField("successMapKey");
+ operation = connection.getHeaderField("operation");
+ } else {
+ isSuccess = SUCCESS;
+ }
+ if (SUCCESS.equals(isSuccess)) {
+ if ("update".equals(operation)) {
+ response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName")
+ + " was successfully updated. ";
+ if (connection.getHeaderField("safetyChecker")!=null) {
+ response = response + "\nPolicy Safety Checker Warning: This closedLoopControlName ("
+ + connection.getHeaderField("newCLName") + ") " + "is potentially in conflict with " + connection.getHeaderField("conflictCLName")
+ + "that already exists." + "See detailed information on ClosedLoop Pairs below: "
+ +"\n"+connection.getHeaderField("safetyChecker");
+ }
+ } else if ("create".equals(operation)) {
+ response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName")
+ + " was successfully created.";
+ if (connection.getHeaderField("safetyChecker")!=null) {
+ response = response + "\nPolicy Safety Checker Warning: This closedLoopControlName ("
+ + connection.getHeaderField("newCLName") + ") " + "is potentially in conflict with " + connection.getHeaderField("conflictCLName")
+ + "that already exists." + "See detailed information on ClosedLoop Pairs below: "
+ +"\n"+connection.getHeaderField("safetyChecker");
+ }
+ } else if ("delete".equals(operation)) {
+ response = "Transaction ID: " + requestID + " --The policy was successfully deleted.";
+ } else if ("import".equals(operation)) {
+ response = "Transaction ID: " + requestID + " --The policy engine import for "+ connection.getHeaderField("service")
+ + " was successfull.";
+ } else if ("createDictionary".equals(operation)) {
+ response = "Transaction ID: " + requestID + " --Dictionary Item was added successfully!";
+ } else if ("updateDictionary".equals(operation)) {
+ response = "Transaction ID: " + requestID + " --Dictionary Item was updated successfully!";
+ } else if ("getDictionary".equals(operation)) {
+ String json = null;
+ try {
+
+ //get the json string from the response
+ InputStream is = connection.getInputStream();
+
+ // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
+ java.util.Scanner scanner = new java.util.Scanner(is);
+ scanner.useDelimiter("\\A");
+ json = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+
+ } catch (IOException e1) {
+ LOGGER.error(e1.getMessage());
+ }
+ response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json;
+ } else if ("getMetrics".equals(operation)) {
+ response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved " + connection.getHeaderField("metrics");
+ }
+ LOGGER.info(response);
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Operation unsuccessful, unable to complete the request!";
+ LOGGER.error(message);
+ response = message;
+ }
+ } else if (connection.getResponseCode() == 202) {
+ if ("delete".equalsIgnoreCase(connection.getHeaderField("operation")) &&
+ "true".equals(connection.getHeaderField("lockdown"))) {
+ response = "Transaction ID: "
+ + requestID
+ + " --Policies are locked down, please try again later.";
+ LOGGER.warn(response);
+ }
+ } else if (connection.getResponseCode() == 204) {
+ if ("push".equals(connection.getHeaderField("operation"))) {
+ response = "Transaction ID: "
+ + requestID
+ + " --Policy '"
+ + connection.getHeaderField("policyId")
+ + "' was successfully pushed to the PDP group '"
+ + connection.getHeaderField("groupId") + "'.";
+ LOGGER.info(response);
+ }
+ } else if (connection.getResponseCode() == 400 && connection.getHeaderField("error") != null) {
+ response = connection.getHeaderField("error");
+ LOGGER.error(response);
+ } else if (connection.getResponseCode() == 403) {
+ response = XACMLErrorConstants.ERROR_PERMISSIONS
+ + "response code of the URL is "
+ + connection.getResponseCode()
+ + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
+ LOGGER.error(response);
+ } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error") != null) {
+ if ("unknownGroupId".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + connection.getHeaderField("message")
+ + " Please check the pdpGroup you are requesting to move the policy to.";
+ LOGGER.error(response);
+ }
+ } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error") != null) {
+ if ("modelExistsDB".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Import Value Exist Error: The import value "
+ + connection.getHeaderField("service")
+ + " already exist on the PAP. "
+ + "Please create a new import value.";
+ } else if ("policyExists".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Policy Exist Error: The Policy "
+ + connection.getHeaderField("policyName")
+ + " already exist on the PAP. "
+ + "Please create a new policy or use the update API to modify the existing one.";
+ } else if ("dictionaryItemExists".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Dictionary Item Exist Error: The Dictionary Item already exist in the database. "
+ + "Please create a new Dictionary Item or use the update API to modify the existing one.";
+ } else if ("duplicateGroup".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Group Policy Scope List Exist Error: The Group Policy Scope List for this Dictionary Item already exist in the database. "
+ + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. "
+ + "Please review the request and verify that the groupPolicyScopeListData1 is unique compared to existing groups.";
+ }
+ LOGGER.error(response);
+ } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) {
+ if ("jpautils".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "Could not create JPAUtils instance on the PAP";
+ } else if ("deleteDB".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "Failed to delete Policy from database.";
+ } else if ("deleteFile".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Cannot delete the policy file";
+ } else if ("groupUpdate".equals(connection.getHeaderField("error"))) {
+ response = connection.getHeaderField("message");
+ } else if ("unknown".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_UNKNOWN
+ + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.";
+ } else if ("deleteConfig".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Cannot delete the configuration or action body file in specified location.";
+ } else if ("missing".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Failed to create value in database because service does match a value in file";
+ } else if ("importDB".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Database errors during policy engine import";
+ } else if ("policyCopyError".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_PROCESS_FLOW
+ + connection.getHeaderField("message");
+ } else if ("addGroupError".equals(connection.getHeaderField("error"))) {
+ response = connection.getHeaderField("message");
+ } else if ("error".equals(connection.getHeaderField("error"))) {
+ response = XACMLErrorConstants.ERROR_UNKNOWN
+ + "Could not create or update the policy for and unknown reason";
+ }
+ LOGGER.error(response);
+ } else {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect.";
+ LOGGER.error(response);
+ }
+ return response;
+ }
+
+ private String checkParameter(String[] parameters, String fullURL) {
+ if (parameters != null && parameters.length > 0) {
+ String queryString = "";
+ for (String p : parameters) {
+ queryString += "&" + p;
+ if (p.equalsIgnoreCase("operation=post")) {
+ requestMethod = "POST";
+ } else if (p.equalsIgnoreCase("operation=delete")) {
+ requestMethod = "DELETE";
+ operation = "delete";
+ } else if (p.equalsIgnoreCase("operation=get")) {
+ requestMethod = "GET";
+ operation = "get";
+ } else if (p.equalsIgnoreCase("operation=put")||p.equalsIgnoreCase("operation=create")
+ ||p.equalsIgnoreCase("operation=update")||p.equalsIgnoreCase("operation=createDictionary")){
+ requestMethod = "PUT";
+ if (p.equalsIgnoreCase("operation=create")) {
+ operation = "create";
+ } else if (p.equalsIgnoreCase("operation=update")) {
+ operation = "update";
+ } else if (p.equalsIgnoreCase("operation=createDictionary")){
+ operation = "createDictionary";
+ }
+ }else if (p.equalsIgnoreCase("importService=MICROSERVICE")||p.equalsIgnoreCase("importService=BRMSPARAM")){
+ requestMethod = "PUT";
+ }
+ }
+ fullURL += "?" + queryString.substring(1);
+ }
+ return fullURL;
+ }
+
+ public StdPDPPolicy pushPolicy(String policyScope, String filePrefix,
+ String policyName, String clientScope, String pdpGroup,
+ UUID requestID) throws PolicyException {
+ String json = "{ "
+ + "\"apiflag\": \"api\","
+ + "\"policyScope\": \""+policyScope+"\","
+ + "\"filePrefix\": \""+filePrefix+"\","
+ + "\"policyName\": \""+policyName+"\","
+ + "\"clientScope\": \""+clientScope+"\","
+ + "\"pdpGroup\": \""+pdpGroup+"\"}";
+ //String response = null;
+ HttpURLConnection connection = null;
+ responseCode = 0;
+ if (paps == null || paps.isEmpty()) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.";
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ int papsCount = 0;
+ boolean connected = false;
+ while (papsCount < paps.size()) {
+ try {
+ String fullURL = getPAP();
+ fullURL = (fullURL.endsWith("/"))? fullURL+"ecomp/pushPolicy" : fullURL+"/ecomp/pushPolicy";
+ URL url = new URL(fullURL);
+ LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---");
+ // Open the connection
+ connection = (HttpURLConnection) url.openConnection();
+ // Setting Content-Type
+ connection.setRequestProperty("Content-Type","application/json");
+ // Adding Authorization
+ connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding());
+ connection.setRequestProperty("Environment", environment);
+ connection.setRequestProperty("ClientScope", clientScope);
+ // set the method and headers
+ connection.setRequestMethod("POST");
+ connection.setUseCaches(false);
+ connection.setInstanceFollowRedirects(false);
+ connection.setDoOutput(true);
+ // Adding RequestID
+ if (requestID == null) {
+ requestID = UUID.randomUUID();
+ LOGGER.info("No request ID provided, sending generated ID: "
+ + requestID.toString());
+ } else {
+ LOGGER.info("Using provided request ID: "
+ + requestID.toString());
+ }
+ connection.setRequestProperty("X-ECOMP-RequestID",
+ requestID.toString());
+ // DO the connect
+ try (OutputStream os = connection.getOutputStream()) {
+ int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("copied to output, bytes=" + count);
+ }
+ }
+ connection.connect();
+ responseCode = connection.getResponseCode();
+ // If Connected to PAP then break from the loop and continue
+ // with the Request
+ if (connection.getResponseCode() > 0 || junit) {
+ connected = true;
+ break;
+ } else {
+ LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode());
+ rotatePAPList();
+ }
+ } catch (Exception e) {
+ // This means that the PAP is not working
+ if (junit) {
+ connected = true;
+ break;
+ }
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "PAP connection Error : " + e);
+ rotatePAPList();
+ }
+ papsCount++;
+ }
+ if (connected) {
+ // Read the Response
+ LOGGER.debug("connected to the PAP : " + getPAP());
+ LOGGER.debug("--- Response: ---");
+ Map<String, List<String>> headers = connection.getHeaderFields();
+ for (String key : headers.keySet()) {
+ LOGGER.debug("Header :" + key + " Value: " + headers.get(key));
+ }
+ try {
+ if(responseCode==202){
+ StdPDPPolicy policy = (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject();
+ return policy;
+ }
+ } catch (IOException | ClassNotFoundException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ throw new PolicyException(
+ XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "Decoding the result ", e);
+ }
+ return null;
+ } else {
+ return null;
+ }
+ }
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java
new file mode 100644
index 000000000..4476b388b
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java
@@ -0,0 +1,398 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.net.MalformedURLException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+
+import javax.json.Json;
+import javax.json.JsonReader;
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.apache.commons.io.IOUtils;
+import org.openecomp.policy.api.PolicyConfigStatus;
+import org.openecomp.policy.api.PolicyDecision;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PolicyResponseStatus;
+import org.openecomp.policy.api.PolicyType;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.XACMLPdpServlet;
+import org.openecomp.policy.pdp.rest.api.models.PDPResponse;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.std.Matches;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.w3c.dom.Document;
+
+import com.att.research.xacml.api.Advice;
+import com.att.research.xacml.api.AttributeAssignment;
+import com.att.research.xacml.api.Decision;
+import com.att.research.xacml.api.Obligation;
+import com.att.research.xacml.api.Request;
+import com.att.research.xacml.api.Response;
+import com.att.research.xacml.api.Result;
+import com.att.research.xacml.api.pdp.PDPEngine;
+import com.att.research.xacml.std.json.JSONRequest;
+import com.att.research.xacml.std.json.JSONResponse;
+import com.att.research.xacml.util.XACMLProperties;
+
+public class PDPServices {
+ private static Logger LOGGER = FlexLogger.getLogger(PDPServices.class.getName());
+ // Change the default Priority value here.
+ private static final int DEFAULT_PRIORITY = 9999;
+ private boolean unique = false;
+ private Boolean decide = false;
+ private Matches match = null;
+
+ public Collection<PDPResponse> generateRequest(String jsonString, UUID requestID, boolean unique, boolean decide) throws PolicyException{
+ this.unique = unique;
+ this.decide = decide;
+ Collection<PDPResponse> results = null;
+ Response response = null;
+ // Create Request. We need XACML API here.
+ try {
+ Request request = JSONRequest.load(jsonString);
+ // Call the PDP
+ LOGGER.debug("--- Generating Request: ---\n" + JSONRequest.toString(request));
+ response = callPDP(request, requestID);
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
+ PDPResponse pdpResponse = new PDPResponse();
+ results = new HashSet<PDPResponse>();
+ pdpResponse.setPolicyConfigMessage("Unable to Call PDP. Error with the URL");
+ pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
+ pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED);
+ results.add(pdpResponse);
+ throw new PolicyException(e);
+ }
+ if (response != null) {
+ results = checkResponse(response);
+ } else {
+ LOGGER.debug("No Response Received from PDP");
+ PDPResponse pdpResponse = new PDPResponse();
+ results = new HashSet<PDPResponse>();
+ pdpResponse.setPolicyConfigMessage("No Response Received");
+ pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
+ pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED);
+ results.add(pdpResponse);
+ }
+ return results;
+ }
+
+ private Collection<PDPResponse> checkResponse(Response response) throws PolicyException{
+ String pdpConfigLocation = null;
+ Collection<PDPResponse> combinedResult = new HashSet<PDPResponse>();
+ int priority = DEFAULT_PRIORITY;
+ Map<Integer, PDPResponse> uniqueResult = new HashMap<Integer, PDPResponse>();
+ for (Result result : response.getResults()) {
+ if (!result.getDecision().equals(Decision.PERMIT)) {
+ LOGGER.debug("Decision not a Permit. " + result.getDecision().toString());
+ PDPResponse pdpResponse = new PDPResponse();
+ if (decide) {
+ pdpResponse.setDecision(PolicyDecision.DENY);
+ for(Advice advice: result.getAssociatedAdvice()){
+ for(AttributeAssignment attribute: advice.getAttributeAssignments()){
+ pdpResponse.setDetails(attribute.getAttributeValue().getValue().toString());
+ break;
+ }
+ }
+ combinedResult.add(pdpResponse);
+ return combinedResult;
+ }
+ pdpResponse.setStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",PolicyResponseStatus.NO_ACTION_REQUIRED,PolicyConfigStatus.CONFIG_NOT_FOUND);
+ combinedResult.add(pdpResponse);
+ return combinedResult;
+ } else {
+ if (decide) {
+ // check for Decision for decision based calls.
+ PDPResponse pdpResponse = new PDPResponse();
+ pdpResponse.setDecision(PolicyDecision.PERMIT);
+ pdpResponse.setDetails("Decision Permit. OK!");
+ combinedResult.add(pdpResponse);
+ return combinedResult;
+ }
+ if (!result.getAssociatedAdvice().isEmpty()) {
+ // Configurations should be in advice.
+ // Also PDP took actions could be here.
+ for (Advice advice : result.getAssociatedAdvice()) {
+ int config = 0, uri = 0;
+ String configURL = null;
+ String policyName = null;
+ String policyVersion = null;
+ match = new Matches();
+ Map<String, String> matchingConditions = new HashMap<String, String>();
+ Map<String, String> configAttributes = new HashMap<String, String>();
+ Map<String, String> responseAttributes = new HashMap<String,String>();
+ Map<String, String> actionTaken = new HashMap<String, String>();
+ PDPResponse pdpResponse = new PDPResponse();
+ Map<String, String> adviseAttributes = new HashMap<String, String>();
+ for (AttributeAssignment attribute : advice.getAttributeAssignments()) {
+ adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString());
+ if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("CONFIGURATION")) {
+ config++;
+ } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) {
+ uri++;
+ if (uri == 1) {
+ configURL = attribute.getAttributeValue().getValue().toString();
+ pdpConfigLocation = configURL.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS));
+ } else {
+ if (!(attribute.getIssuer().equalsIgnoreCase("PDP"))) {
+ throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy");
+ }
+ }
+ } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("PolicyName")) {
+ policyName = attribute.getAttributeValue().getValue().toString();
+ } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("VersionNumber")) {
+ policyVersion = attribute.getAttributeValue().getValue().toString();
+ } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("Priority")){
+ try{
+ priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString());
+ } catch(Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value");
+ priority = DEFAULT_PRIORITY;
+ }
+ } else if (attribute.getAttributeId().stringValue().startsWith("matching")) {
+ matchingConditions.put(attribute.getAttributeId().stringValue()
+ .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString());
+ if (attribute.getAttributeId().stringValue()
+ .replaceFirst("(matching).", "").equals("ECOMPName")) {
+ match.setEcompName(attribute.getAttributeValue().getValue().toString());
+ } else if (attribute.getAttributeId().stringValue()
+ .replaceFirst("(matching).", "").equals("ConfigName")) {
+ match.setConfigName(attribute.getAttributeValue().getValue().toString());
+ } else {
+ configAttributes.put(attribute.getAttributeId().stringValue()
+ .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString());
+ }
+ } else if (attribute.getAttributeId().stringValue().startsWith("key:")) {
+ responseAttributes.put(attribute.getAttributeId().stringValue().replaceFirst("(key).", ""),
+ attribute.getAttributeValue().getValue().toString());
+ } else if (attribute.getAttributeId().stringValue().startsWith("controller:")) {
+ responseAttributes.put("$"+ attribute.getAttributeId().stringValue(),
+ attribute.getAttributeValue().getValue().toString());
+ } else if (attribute.getAttributeId().stringValue().startsWith("dependencies:")) {
+ responseAttributes.put("$dependency$",
+ attribute.getAttributeValue().getValue().toString());
+ }
+ }
+ if (!configAttributes.isEmpty()) {
+ match.setConfigAttributes(configAttributes);
+ }
+ if ((config == 1) && (uri == 1)) {
+ // If there is a configuration.
+ try {
+ LOGGER.debug("Configuration Call to : " + configURL);
+ pdpResponse = configCall(pdpConfigLocation);
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ e);
+ pdpResponse.setStatus("Error in Calling the Configuration URL "+ e,
+ PolicyResponseStatus.NO_ACTION_REQUIRED,
+ PolicyConfigStatus.CONFIG_NOT_FOUND);
+ }
+ pdpResponse.setPolicyName(policyName);
+ pdpResponse.setPolicyVersion(policyVersion);
+ pdpResponse.setMatchingConditions(matchingConditions);
+ pdpResponse.setResponseAttributes(responseAttributes);
+ if(!unique){
+ combinedResult.add(pdpResponse);
+ }else{
+ if(!uniqueResult.isEmpty()){
+ if(uniqueResult.containsKey(priority)){
+ // Not any more unique, check the matching conditions size
+ int oldSize = uniqueResult.get(priority).getMatchingConditions().size();
+ int newSize = matchingConditions.size();
+ if(oldSize < newSize){
+ uniqueResult.put(priority, pdpResponse);
+ }else if(oldSize == newSize){
+ pdpResponse = new PDPResponse();
+ pdpResponse.setStatus("Two/more Policies have Same Priority and matching conditions, Please correct your policies.",
+ PolicyResponseStatus.NO_ACTION_REQUIRED,
+ PolicyConfigStatus.CONFIG_NOT_FOUND);
+ combinedResult.add(pdpResponse);
+ unique = false;
+ return combinedResult;
+ }
+ }else{
+ uniqueResult.put(priority, pdpResponse);
+ }
+ }else{
+ uniqueResult.put(priority, pdpResponse);
+ }
+ }
+ } else {
+ // Else it is Action Taken.
+ LOGGER.info("Action Taken by PDP. ");
+ actionTaken.putAll(adviseAttributes);
+ pdpResponse.setActionTaken(actionTaken);
+ pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_TAKEN);
+ pdpResponse.setPolicyResponseMessage("Action Taken by the PDP");
+ combinedResult.add(pdpResponse);
+ }
+ }
+ }
+ if (!result.getObligations().isEmpty()) {
+ // Obligation actions
+ // Action advised should be in obligations.
+ for (Obligation obligation : result.getObligations()) {
+ Map<String, String> actionAdvised = new HashMap<String, String>();
+ PDPResponse pdpResponse = new PDPResponse();
+ for (AttributeAssignment attribute : obligation.getAttributeAssignments()) {
+ actionAdvised.put(attribute.getAttributeId().stringValue(),
+ attribute.getAttributeValue().getValue().toString());
+ }
+ pdpResponse.setActionAdvised(actionAdvised);
+ pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_ADVISED);
+ pdpResponse.setPolicyResponseMessage("Action has been Advised ");
+ combinedResult.add(pdpResponse);
+ }
+ }
+ }
+ }
+ if(unique){
+ // Select Unique policy.
+ int minNum = DEFAULT_PRIORITY;
+ for(int num: uniqueResult.keySet()){
+ if(num < minNum){
+ minNum = num;
+ }
+ }
+ combinedResult.add(uniqueResult.get(minNum));
+ // Turn off Unique
+ unique = false;
+ }
+
+ return combinedResult;
+ }
+
+ private PDPResponse configCall(String pdpConfigLocation) throws Exception{
+ PDPResponse pdpResponse = new PDPResponse();
+ if(pdpConfigLocation.contains("/")){
+ pdpConfigLocation = pdpConfigLocation.replace("/", File.separator);
+ }
+ try {
+ InputStream inputStream = new FileInputStream(new File(pdpConfigLocation));
+ try {
+ if (pdpConfigLocation.endsWith("json")) {
+ pdpResponse.setType(PolicyType.JSON);
+ JsonReader jsonReader = Json.createReader(inputStream);
+ pdpResponse.setConfig(jsonReader.readObject().toString());
+ jsonReader.close();
+ } else if (pdpConfigLocation.endsWith("xml")) {
+ pdpResponse.setType(PolicyType.XML);
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ DocumentBuilder db = null;
+ try {
+ db = dbf.newDocumentBuilder();
+ Document document = db.parse(inputStream);
+ DOMSource domSource = new DOMSource(document);
+ StringWriter writer = new StringWriter();
+ StreamResult result = new StreamResult(writer);
+ TransformerFactory tf = TransformerFactory.newInstance();
+ Transformer transformer;
+ transformer = tf.newTransformer();
+ transformer.transform(domSource, result);
+ pdpResponse.setConfig(writer.toString());
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e);
+ throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e);
+ }
+ } else if (pdpConfigLocation.endsWith("properties")) {
+ pdpResponse.setType(PolicyType.PROPERTIES);
+ Properties configProp = new Properties();
+ configProp.load(inputStream);
+ Map<String, String> propVal = new HashMap<String, String>();
+ for(String name: configProp.stringPropertyNames()) {
+ propVal.put(name, configProp.getProperty(name));
+ }
+ pdpResponse.setProperty(propVal);
+ } else if (pdpConfigLocation.endsWith("txt")) {
+ pdpResponse.setType(PolicyType.OTHER);
+ String other = IOUtils.toString(inputStream);
+ IOUtils.closeQuietly(inputStream);
+ pdpResponse.setConfig(other);
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found");
+ pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
+ pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found.");
+ inputStream.close();
+ return pdpResponse;
+ }
+ LOGGER.info("config Retrieved " + pdpConfigLocation);
+ pdpResponse.setStatus("Config Retrieved! ",
+ PolicyResponseStatus.NO_ACTION_REQUIRED,
+ PolicyConfigStatus.CONFIG_RETRIEVED);
+ return pdpResponse;
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ throw new Exception(XACMLErrorConstants.ERROR_PROCESS_FLOW +
+ "Cannot open a connection to the configURL", e);
+ }
+ } catch (MalformedURLException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e);
+ }
+ }
+
+ private Response callPDP(Request request,
+ UUID requestID) throws Exception{
+ Response response = null;
+ // Get the PDPEngine
+ if (requestID == null) {
+ requestID = UUID.randomUUID();
+ LOGGER.debug("No request ID provided, sending generated ID: " + requestID.toString());
+ } else {
+ LOGGER.debug("Using provided request ID: " + requestID.toString());
+ }
+ PDPEngine pdpEngine = XACMLPdpServlet.getPDPEngine();
+ if (pdpEngine == null) {
+ String message = "PDPEngine not loaded.";
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message);
+ return response;
+ }
+ // call the PDPEngine to decide and give the response on the Request.
+ try {
+ response = pdpEngine.decide(request);
+ LOGGER.debug("Response from the PDP is: \n" + JSONResponse.toString(response));
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ return null;
+ }
+ return response;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java
new file mode 100644
index 000000000..38a0da32e
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java
@@ -0,0 +1,186 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.UUID;
+
+import org.openecomp.policy.api.ImportParameters;
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.ImportParameters.IMPORT_TYPE;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.utils.PolicyUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.multipart.MultipartFile;
+
+public class PolicyEngineImportService {
+ private static Logger LOGGER = FlexLogger.getLogger(PolicyEngineImportService.class.getName());
+
+ private String importResponse = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private String message = null;
+ private ImportParameters importParameters = null;
+ private MultipartFile file = null;
+
+ public PolicyEngineImportService(String importParametersJson,
+ MultipartFile file,
+ String requestID) {
+ try {
+ this.importParameters = PolicyUtils.jsonStringToObject(importParametersJson, ImportParameters.class);
+ } catch (Exception e) {
+ importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
+ status = HttpStatus.BAD_REQUEST;
+ // This needs to stop here in case if there a issue here. Avoiding Null pointer exceptions.
+ return;
+ }
+ this.file = file;
+ if(importParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.importParameters.setRequestID(requestUUID);
+ }
+ try{
+ run();
+ specialCheck();
+ }catch(PolicyException e){
+ importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void specialCheck() {
+ if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){
+ status = HttpStatus.BAD_REQUEST;
+ }else if(importResponse.contains("PE200")){
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
+ }
+ }
+
+ private void run() throws PolicyException{
+ // Check Validation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ // Get Result.
+ try{
+ status = HttpStatus.OK;
+ importResponse = processResult();
+ }catch (Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyException(e);
+ }
+ }
+
+ private String processResult() throws PolicyException{
+ String response = null;
+ InputStream targetStream = null;
+ String fileName = file.getOriginalFilename();
+ switch (importParameters.getServiceType()){
+ case MICROSERVICE:
+ if (fileName.endsWith(".xmi") || fileName.endsWith(".zip")){
+ try {
+ targetStream = new BufferedInputStream(file.getInputStream());
+ } catch (IOException e) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided";
+ LOGGER.error(response + e);
+ return response;
+ }
+ }else{
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .xmi or .zip.";
+ LOGGER.error(response);
+ return response;
+ }
+ break;
+ case BRMSPARAM:
+ if (fileName.endsWith(".drl")){
+ try {
+ targetStream = new BufferedInputStream(file.getInputStream());
+ } catch (IOException e) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided";
+ LOGGER.error(response + e);
+ return response;
+ }
+ }else{
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .drl";
+ LOGGER.error(response);
+ return response;
+ }
+ break;
+ default:
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect ServiceType Given. ";
+ LOGGER.error(response);
+ return response;
+ }
+ String[] parameters = new String[] {"importService=" + importParameters.getServiceType(), "serviceName="
+ + importParameters.getServiceName(), "fileName=" + fileName, "version=" + importParameters.getVersion(), "description=" + importParameters.getDescription()};
+ PAPServices papServices = new PAPServices();
+ response = (String) papServices.callPAP(targetStream, parameters, importParameters.getRequestID(), "importMS");
+ return response;
+ }
+
+ private boolean getValidation() {
+ if(importParameters==null){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + " no Import Parameters given. ";
+ return false;
+ }
+ if(importParameters.getServiceName()==null || importParameters.getServiceName().trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service name value.";
+ return false;
+ }
+ if(importParameters.getServiceType()==null || importParameters.getServiceType().toString().trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service Type value.";
+ return false;
+ }
+ if(importParameters.getServiceType().equals(IMPORT_TYPE.MICROSERVICE) && (importParameters.getVersion()==null || importParameters.getVersion().trim().isEmpty())){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing version value.";
+ return false;
+ }
+ if(file==null || file.isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing File.";
+ return false;
+ }
+ return true;
+ }
+
+ public String getResult() {
+ return importResponse;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java
new file mode 100644
index 000000000..ee8683f1f
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java
@@ -0,0 +1,261 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.UUID;
+
+import org.openecomp.policy.api.PolicyException;
+import org.openecomp.policy.api.PushPolicyParameters;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
+import org.springframework.http.HttpStatus;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDPPolicy;
+
+public class PushPolicyService {
+ private static Logger LOGGER = FlexLogger.getLogger(PushPolicyService.class.getName());
+
+ private String pushResult = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private PushPolicyParameters pushPolicyParameters = null;
+ private String message = null;
+ private String policyName = null;
+ private String policyScope = null;
+ private String pdpGroup = null;
+ private String policyType = null;
+ private String filePrefix = null;
+ private String clientScope = null;
+
+ public PushPolicyService(PushPolicyParameters pushPolicyParameters,
+ String requestID) {
+ this.pushPolicyParameters = pushPolicyParameters;
+ if(pushPolicyParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.pushPolicyParameters.setRequestID(requestUUID);
+ }
+ try{
+ run();
+ specialCheck();
+ }catch(PolicyException e){
+ pushResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void specialCheck() {
+ if(pushResult.contains("BAD REQUEST") || pushResult.contains("PE300")){
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void run() throws PolicyException{
+ // Check Validation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyException(message);
+ }
+ // Process Results.
+ try{
+ status = HttpStatus.OK;
+ pushResult = processResult();
+ }catch(Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyException(e);
+ }
+ }
+
+ private String processResult() throws PolicyException{
+ PAPServices papServices = new PAPServices();
+ String response = null;
+ StdPDPPolicy selectedPolicy = papServices.pushPolicy(policyScope, filePrefix, policyName, clientScope, pdpGroup, pushPolicyParameters.getRequestID());
+ if(selectedPolicy==null){
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. "
+ + "This indicates a problem with getting the version from the PAP or the policy does not exist.";
+ LOGGER.error(response);
+ return response;
+ }
+ /* //String activeVersion = papServices.getActiveVersion(policyScope, filePrefix, policyName, clientScope, pushPolicyParameters.getRequestID());
+ LOGGER.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion);
+ String id = null;
+ if ("pe100".equalsIgnoreCase(activeVersion)) {
+ response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
+ + "Contact Administrator for this Scope. ";
+ LOGGER.error(response);
+ return response;
+ } else if ("pe300".equalsIgnoreCase(activeVersion)) {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. "
+ + "This indicates a problem with getting the version from the PAP or the policy does not exist.";
+ LOGGER.error(response);
+ return response;
+ }
+ if (!activeVersion.equalsIgnoreCase("0")) {
+ id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml";
+ LOGGER.debug("The policyId is " + id);
+ } else {
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. "
+ + "This indicates the policy does not exist, please verify the policy exists.";
+ LOGGER.error(response);
+ return response;
+ }
+ StdPDPPolicy selectedPolicy = papServices.getGitPath(policyScope, filePrefix, policyName, activeVersion, clientScope, pushPolicyParameters.getRequestID(), id);
+ */
+ try {
+ LOGGER.debug("StdPDPPolicy object contains: " + selectedPolicy.getId() + ", " + selectedPolicy.getName() + ", " + selectedPolicy.getLocation().toString());
+ response = copyPolicy(selectedPolicy, pdpGroup, clientScope, pushPolicyParameters.getRequestID());
+ } catch (PAPException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+e.getMessage());
+ throw new PolicyException(e);
+ }
+ LOGGER.debug("copyPolicy response: " + response);
+ if(response.contains("successfully")){
+ response = (String) papServices.callPAP(selectedPolicy, new String[]{"groupId=" + pdpGroup, "policyId="+selectedPolicy.getId(), "apiflag=addPolicyToGroup", "operation=PUT"}, pushPolicyParameters.getRequestID(), clientScope);
+ }
+ LOGGER.debug("Final API response: " + response);
+ return response;
+ }
+
+ private String copyPolicy(PDPPolicy policy, String group, String policyType, UUID requestID) throws PAPException {
+ String response = null;
+ if (policy == null || group == null) {
+ throw new PAPException("Null input policy="+policy+" group="+group);
+ }
+ try {
+ StdPAPPolicy location = new StdPAPPolicy(policy.getLocation());
+ response = copyFile(policy.getId(), group, location, policyType, requestID);
+ } catch (Exception e) {
+ String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
+ throw new PAPException(message);
+ }
+ return response;
+ }
+
+ private String copyFile(String policyId, String group, StdPAPPolicy location, String clientScope, UUID requestID) throws PAPException {
+ String response = null;
+ // send the policy file to the PAP Servlet
+ PAPServices papService = new PAPServices();
+ try {
+ response = (String) papService.callPAP(location, new String[] {"groupId=" + group, "policyId="+policyId, "apiflag=api", "operation=post"}, requestID, clientScope);
+ } catch (Exception e) {
+ String message = "Unable to PUT policy '" + policyId + "', e:" + e;
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
+ throw new PAPException(message);
+ }
+ return response;
+ }
+
+ private boolean getValidation() {
+ // While Validating, extract the required values.
+ if (pushPolicyParameters.getPolicyName() != null
+ && pushPolicyParameters.getPolicyName().contains(".")) {
+ policyName = pushPolicyParameters.getPolicyName().substring(pushPolicyParameters.getPolicyName().lastIndexOf(".") + 1,
+ pushPolicyParameters.getPolicyName().length());
+ policyScope = pushPolicyParameters.getPolicyName().substring(0,pushPolicyParameters.getPolicyName().lastIndexOf("."));
+ LOGGER.info("Name is " + policyName + " scope is " + policyScope);
+ } else {
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
+ return false;
+ }
+ if (policyName==null||policyName.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
+ return false;
+ }
+ policyType = pushPolicyParameters.getPolicyType();
+ if(policyType== null || policyType.trim().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given.";
+ return false;
+ }
+
+ setClientScope();
+ if(clientScope==null){
+ return false;
+ }
+
+ pdpGroup = pushPolicyParameters.getPdpGroup();
+ if(pdpGroup==null || pdpGroup.trim().isEmpty()){
+ pdpGroup = "default";
+ }
+
+ LOGGER.debug("clientScope is " + clientScope);
+ LOGGER.debug("filePrefix is " + filePrefix);
+
+ return true;
+ }
+
+ private void setClientScope() {
+ if ("Firewall".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigFirewall";
+ filePrefix = "Config_FW_";
+ } else if ("Action".equalsIgnoreCase(policyType)) {
+ clientScope = "Action";
+ filePrefix = "Action_";
+ } else if ("Decision".equalsIgnoreCase(policyType)) {
+ clientScope = "Decision";
+ filePrefix = "Decision_";
+ } else if ("Base".equalsIgnoreCase(policyType)) {
+ clientScope = "Config";
+ filePrefix = "Config_";
+ } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigClosedLoop";
+ filePrefix = "Config_Fault_";
+ } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigClosedLoop";
+ filePrefix = "Config_PM_";
+ } else if ("MicroService".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigMS";
+ filePrefix = "Config_MS_";
+ } else if ("BRMS_RAW".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigBrmsRaw";
+ filePrefix = "Config_BRMS_Raw_";
+ } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) {
+ clientScope = "ConfigBrmsParam";
+ filePrefix = "Config_BRMS_Param_";
+ } else {
+ clientScope = null;
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType
+ + " is not a valid Policy Type.";
+ }
+ }
+
+ public String getResult() {
+ return pushResult;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java
new file mode 100644
index 000000000..4659ead5c
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java
@@ -0,0 +1,171 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.services;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.json.Json;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+
+import org.openecomp.policy.api.EventRequestParameters;
+import org.openecomp.policy.api.PolicyEventException;
+import org.openecomp.policy.api.PolicyResponse;
+import org.openecomp.policy.api.PolicyResponseStatus;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.pdp.rest.api.models.PDPResponse;
+import org.openecomp.policy.std.StdPolicyResponse;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.http.HttpStatus;
+
+public class SendEventService {
+ private static Logger LOGGER = FlexLogger.getLogger(SendEventService.class.getName());
+
+ private Collection<PolicyResponse> policyResponses = null;
+ private HttpStatus status = HttpStatus.BAD_REQUEST;
+ private EventRequestParameters eventRequestParameters = null;
+ private String message = null;
+
+ public SendEventService(EventRequestParameters eventRequestParameters,
+ String requestID) {
+ this.eventRequestParameters=eventRequestParameters;
+ if(eventRequestParameters.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ } catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ LOGGER.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ this.eventRequestParameters.setRequestID(requestUUID);
+ }
+ policyResponses = new ArrayList<PolicyResponse>();
+ try{
+ run();
+ }catch(PolicyEventException e){
+ StdPolicyResponse policyResponse = new StdPolicyResponse();
+ policyResponse.setPolicyResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+e);
+ policyResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED);
+ policyResponses.add(policyResponse);
+ status = HttpStatus.BAD_REQUEST;
+ }
+ }
+
+ private void run() throws PolicyEventException{
+ // getValidation.
+ if(!getValidation()){
+ LOGGER.error(message);
+ throw new PolicyEventException(message);
+ }
+ // Generate Request.
+ String modelString = getModel().toString();
+ LOGGER.debug("Generated JSON Request is: " + modelString);
+ // Process Result.
+ try {
+ PDPServices pdpServices = new PDPServices();
+ status = HttpStatus.OK;
+ policyResponses = eventResult(pdpServices.generateRequest(modelString, eventRequestParameters.getRequestID(),false, false));
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ status = HttpStatus.BAD_REQUEST;
+ throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
+ }
+ }
+
+ private Collection<PolicyResponse> eventResult(
+ Collection<PDPResponse> generateRequest) {
+ Collection<PolicyResponse> result = new HashSet<PolicyResponse>();
+ if (generateRequest == null) {
+ return null;
+ }
+ if (!generateRequest.isEmpty()) {
+ for (PDPResponse stdStatus : generateRequest) {
+ StdPolicyResponse policyResponse = new StdPolicyResponse();
+ policyResponse.setActionAdvised(stdStatus.getActionAdvised());
+ policyResponse.setActionTaken(stdStatus.getActionTaken());
+ policyResponse.setPolicyResponseMessage(stdStatus.getPolicyResponseMessage());
+ policyResponse.setPolicyResponseStatus(stdStatus.getPolicyResponseStatus());
+ policyResponse.setRequestAttributes(eventRequestParameters.getEventAttributes());
+ result.add(policyResponse);
+ }
+ }
+ return result;
+ }
+
+ private JsonObject getModel() throws PolicyEventException{
+ JsonArrayBuilder resourceArray = Json.createArrayBuilder();
+ Map<String,String> eventAttributes = eventRequestParameters.getEventAttributes();
+ for (String key : eventAttributes.keySet()) {
+ if (key.isEmpty()) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key";
+ LOGGER.error(message);
+ throw new PolicyEventException(message);
+ }
+ JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
+ if (eventAttributes.get(key).matches("[0-9]+")) {
+ int val = Integer.parseInt(eventAttributes.get(key));
+ resourceBuilder.add("Value", val);
+ } else {
+ resourceBuilder.add("Value", eventAttributes.get(key));
+ }
+ resourceBuilder.add("AttributeId", key);
+ resourceArray.add(resourceBuilder);
+ }
+ JsonObject model = Json
+ .createObjectBuilder()
+ .add("Request", Json.createObjectBuilder()
+ .add("Resource",Json.createObjectBuilder()
+ .add("Attribute",resourceArray)))
+ .build();
+ return model;
+ }
+
+ private boolean getValidation() {
+ if (eventRequestParameters == null) {
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Parameters Given. ";
+ return false;
+ }
+ if (eventRequestParameters.getEventAttributes() == null || eventRequestParameters.getEventAttributes().isEmpty()){
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Attributes Given. ";
+ return false;
+ }
+ return true;
+ }
+
+ public Collection<PolicyResponse> getResult() {
+ return policyResponses;
+ }
+
+ public HttpStatus getResponseCode() {
+ return status;
+ }
+
+}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java
new file mode 100644
index 000000000..984cc907b
--- /dev/null
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pdp.rest.api.utils;
+
+import java.io.StringReader;
+
+import javax.json.Json;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+import javax.json.JsonReader;
+import javax.json.stream.JsonParsingException;
+
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+import com.google.common.base.CharMatcher;
+
+public class PolicyApiUtils {
+ private static Logger LOGGER = FlexLogger.getLogger(PolicyApiUtils.class
+ .getName());
+
+ public static Boolean validateNONASCIICharactersAndAllowSpaces(
+ String jsonString) {
+ Boolean isValidForm = false;
+ if (jsonString.isEmpty()) {
+ LOGGER.error("The Value is empty.");
+ return false;
+ } else {
+ if (CharMatcher.ASCII.matchesAllOf((CharSequence) jsonString)) {
+ LOGGER.info("The Value does not contain ASCII Characters");
+ isValidForm = true;
+ } else {
+ LOGGER.error("The Value Contains Non ASCII Characters");
+ isValidForm = false;
+ }
+ }
+ return isValidForm;
+ }
+
+ public static boolean isNumeric(String str) {
+ for (char c : str.toCharArray()) {
+ if (!Character.isDigit(c))
+ return false;
+ }
+ return true;
+ }
+
+ public static JsonObject stringToJsonObject(String value)
+ throws JsonException, JsonParsingException, IllegalStateException {
+ JsonReader jsonReader = Json.createReader(new StringReader(value));
+ JsonObject object = jsonReader.readObject();
+ jsonReader.close();
+ return object;
+ }
+}