diff options
Diffstat (limited to 'ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services')
26 files changed, 4988 insertions, 0 deletions
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ActionPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ActionPolicyService.java new file mode 100644 index 000000000..66920e0db --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ActionPolicyService.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Action Policy Implementation. + * + * @version 0.1 + */ +public class ActionPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyService.class.getName()); + private 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSParamPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSParamPolicyService.java new file mode 100644 index 000000000..dd2bd452e --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSParamPolicyService.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * BRMS Param Policy Implementation. + * + * @version 0.1 + */ +public class BRMSParamPolicyService{ + private static final Logger LOGGER = FlexLogger.getLogger(BRMSParamPolicyService.class.getName()); + private PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + 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() { + boolean 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSRawPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSRawPolicyService.java new file mode 100644 index 000000000..ea17529ba --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSRawPolicyService.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java new file mode 100644 index 000000000..5817d7410 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Closed Loop Fault Policy Implementation. + * + * @version 0.1 + */ +public class ClosedLoopFaultPolicyService{ + private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopFaultPolicyService.class.getName()); + private 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(); + LOGGER.error("Json Parse Exception.", e); + 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"; + } + // get values and attributes from the JsonObject + if(!configBody.containsKey("onapname")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + LOGGER.error(message); + return message; + } + String onapName = configBody.get("onapname").toString().trim().replace("\"", ""); + if (onapName==null||onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + LOGGER.error(message); + return message; + } + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + LOGGER.error(message); + return message; + } + String jsonBody = configBody.toString(); + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_Fault", policyName, policyParameters.getPolicyDescription(), onapName, + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java new file mode 100644 index 000000000..74c4bd71d --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Closed Loop PM policy Implementation. + * + * @version 0.1 + */ +public class ClosedLoopPMPolicyService{ + private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPMPolicyService.class.getName()); + + private 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(); + LOGGER.error("Error during parsing JSON config body for Closed loop PM policy " , e); + 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 + if(!configBody.containsKey("onapname")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + LOGGER.error(message); + return message; + } + if(!configBody.containsKey("serviceTypePolicyName")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Service Type Policy Name given."; + LOGGER.error(message); + return message; + } + String onapName = configBody.get("onapname").toString().trim().replace("\"", ""); + if (onapName==null||onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + LOGGER.error(message); + return message; + } + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + LOGGER.error(message); + return message; + } + String jsonBody = configBody.toString(); + String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", ""); + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_PM", policyName, policyParameters.getPolicyDescription(), onapName, + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ConfigPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ConfigPolicyService.java new file mode 100644 index 000000000..c8d3d74d1 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ConfigPolicyService.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Config Base Policy Implementation. + * + * @version 0.1 + */ +public class ConfigPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicyService.class.getName()); + private 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 onapName = 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; + } + boolean levelCheck = false; + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + onapName = policyParameters.getOnapName(); + configName = policyParameters.getConfigName(); + if(onapName==null || onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ONAP Name given."; + return false; + } + if(configName==null || configName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given."; + return false; + } + message = PolicyUtils.emptyPolicyValidator(onapName); + 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 ("JSON".equalsIgnoreCase(configType)) { + 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(), onapName, 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java new file mode 100644 index 000000000..d8cca2bb9 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateConfigPolicyService { + private static final 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.setOnapName(configPolicyAPIRequest.getOnapName()); + policyParameters.setConfigName(configPolicyAPIRequest.getConfigName()); + Map<AttributeType, Map<String, String>> attributes = new HashMap<>(); + attributes.put(AttributeType.MATCHING, configPolicyAPIRequest.getConfigAttributes()); + policyParameters.setAttributes(attributes); + if(configPolicyAPIRequest.getConfigType()==null){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy ConfigType given."; + LOGGER.error(message); + throw new PolicyException(message); + } + try{ + policyParameters.setConfigBodyType(PolicyType.valueOf(configPolicyAPIRequest.getConfigType())); + }catch(IllegalArgumentException e){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Improper ConfigType given."; + LOGGER.error(message, e); + throw new PolicyException(message); + } + policyParameters.setConfigBody(configPolicyAPIRequest.getBody()); + policyParameters.setRiskLevel(configPolicyAPIRequest.getRiskLevel()); + policyParameters.setRiskType(configPolicyAPIRequest.getRiskType()); + policyParameters.setGuard(Boolean.parseBoolean(configPolicyAPIRequest.getGuard())); + if(configPolicyAPIRequest.getTtlDate()==null){ + LOGGER.warn("No TTL date given "); + policyParameters.setTtlDate(null); + }else{ + try { + policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configPolicyAPIRequest.getTtlDate())); + } catch (ParseException e) { + LOGGER.warn("Error Parsing date given " + configPolicyAPIRequest.getTtlDate(), e); + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java new file mode 100644 index 000000000..9d2577426 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.io.ByteArrayInputStream; +import java.util.UUID; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateDictionaryService { + private static final 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(),e); + } + }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, e); + return message; + } + String dictionaryFields = json.toString(); + PAPServices papServices = new PAPServices(); + return (String) papServices.callPAP(new ByteArrayInputStream(dictionaryFields.getBytes()), new String[] {"operation="+operation, "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); + } + + 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 && "MicroServiceDictionary".equalsIgnoreCase(dictionaryParameters.getDictionary())&& !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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java new file mode 100644 index 000000000..d4d686a13 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateFirewallPolicyService { + private static final 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(), e); + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyService.java new file mode 100644 index 000000000..0ff5f4a0a --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyService.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import org.onap.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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java new file mode 100644 index 000000000..945cdba8b --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java @@ -0,0 +1,293 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyServiceImpl.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(), e); + } + }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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java new file mode 100644 index 000000000..c283ff14c --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.RuleProvider; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.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 onapName = null; + + public DecisionPolicyService(String policyScope, String policyName, + PolicyParameters policyParameters) { + this.policyScope = policyScope; + this.policyName = policyName; + this.policyParameters = policyParameters; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + onapName = policyParameters.getOnapName(); + if (onapName==null||onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ONAP 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(), onapName, 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java new file mode 100644 index 000000000..01670a5fd --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java @@ -0,0 +1,258 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.io.File; +import java.util.UUID; + +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; +import org.springframework.http.HttpStatus; + +public class DeletePolicyService { + private static final 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(), e); + } + }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("PE200")||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()==null||deletePolicyParameters.getPolicyName().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + 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(); + } + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/FirewallPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/FirewallPolicyService.java new file mode 100644 index 000000000..8f4ba9a79 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/FirewallPolicyService.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Firewall Policy Implementation. + * + * @version 0.1 + */ +public class FirewallPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(FirewallPolicyService.class.getName()); + + private 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 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(); + LOGGER.error("Error while parsing JSON body for creating Firewall Policy " , e); + return false; + } + if(firewallJson==null|| firewallJson.isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config-Body given."; + return false; + } + boolean levelCheck = 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 + if(!firewallJson.containsKey("configName")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No configName given in firwall JSON."; + LOGGER.error(message); + return message; + } + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetConfigService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetConfigService.java new file mode 100644 index 000000000..1817d8861 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetConfigService.java @@ -0,0 +1,318 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Arrays; +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.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.pdp.rest.api.models.PolicyConfig; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetConfigService { + private static final 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(),e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.configRequestParameters.setRequestID(requestUUID); + } + policyConfigs = new ArrayList<>(); + try{ + run(); + specialCheck(); + }catch(PolicyConfigException e){ + LOGGER.error(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.isEmpty()){ + 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<>(); + 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<>(); + 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.getOnapName()!=null && configRequestParameters.getOnapName().trim().length()>0 && config.getMatchingConditions().containsKey("ONAPName")){ + if(!config.getMatchingConditions().get("ONAPName").matches(configRequestParameters.getOnapName())){ + 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(key.equals("RiskType")||key.equals("RiskLevel")||key.equals("guard")||key.equals("TTLDate")){ + continue; + } + if(config.getMatchingConditions().containsKey(key)){ + if(config.getMatchingConditions().get(key).contains(",")){ + List<String> elements = Arrays.asList(config.getMatchingConditions().get(key).split(",")); + if(!elements.contains(configRequestParameters.getConfigAttributes().get(key))){ + flag=true; + } + }else if(!config.getMatchingConditions().get(key).matches(configRequestParameters.getConfigAttributes().get(key))){ + flag = true; + } + }else{ + flag = true; + } + if(flag){ + break; + } + } + if(flag){ + continue; + } + } + } + policyConfig.add(config); + } + if(policyConfig.isEmpty()){ + 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.getOnapName()!=null){ + JsonObjectBuilder subjectBuilder = Json.createObjectBuilder(); + subjectBuilder.add("Value", configRequestParameters.getOnapName()); + subjectBuilder.add("AttributeId", "ONAPName"); + 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("Onap Name is not given. "); + } + return 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(); + } + + 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<>(); + 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.getOnapName()==null && configRequestParameters.getPolicyName()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot proceed without onapComponentName 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java new file mode 100644 index 000000000..66beb0663 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.DecisionResponse; +import org.onap.policy.api.PolicyDecision; +import org.onap.policy.api.PolicyDecisionException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.std.StdDecisionResponse; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetDecisionService { + private static final 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 onapComponentName = 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(),e); + } + }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 (Entry<String,String> key : decisionAttributes.entrySet()) { + if (key.getKey().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(message); + throw new PolicyDecisionException(message); + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (key.getValue().matches("[0-9]+")) { + + if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { + + resourceBuilder.add("Value", key.getValue()); + + } else { + + int val = Integer.parseInt(key.getValue()); + resourceBuilder.add("Value", val); + + } + + } else { + resourceBuilder.add("Value", key.getValue()); + } + resourceBuilder.add("AttributeId", key.getKey()); + resourceArray.add(resourceBuilder); + } + return Json.createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("AccessSubject", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", onapComponentName) + .add("AttributeId", "ONAPName"))) + .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(); + } + + private boolean getValidation() { + if(decisionRequestParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Paramaters"; + return false; + } + onapComponentName = decisionRequestParameters.getONAPComponentName(); + decisionAttributes = decisionRequestParameters.getDecisionAttributes(); + if (onapComponentName == null || onapComponentName.isEmpty()) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No onapComponentName given : " + onapComponentName; + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java new file mode 100644 index 000000000..8f88ef7c7 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java @@ -0,0 +1,276 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.UUID; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.DictionaryResponse; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.std.StdDictionaryResponse; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetDictionaryService { + private static final 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(), e); + } + }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 && (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, e); + 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); + if(result!=null && result.contains("PE200")){ + status=HttpStatus.INTERNAL_SERVER_ERROR; + }else{ + status=HttpStatus.BAD_REQUEST; + } + } + return response; + } + + private String formatDictionaryJson(String result) { + String jsonString = result.substring(82); + String dictionary = dictionaryParameters.getDictionary(); + + switch (dictionary) { + case "OnapName": + jsonString = jsonString.replace("onapNameDictionaryDatas", "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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetMetricsService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetMetricsService.java new file mode 100644 index 000000000..a0a477cdf --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetMetricsService.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.UUID; + +import javax.json.JsonException; + +import org.json.JSONObject; +import org.onap.policy.api.MetricsRequestParameters; +import org.onap.policy.api.MetricsResponse; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.std.StdMetricsResponse; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetMetricsService { + private static final Logger LOGGER = FlexLogger + .getLogger(GetMetricsService.class.getName()); + + private MetricsResponse response = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + 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(), e); + } + } 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 && (response.getResponseMessage() != null + && response.getResponseMessage().contains("PE300"))) { + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyException { + // 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; + String message = 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) { + String jsonString = null; + if(json != null){ + jsonString = json.toString(); + } + message = XACMLErrorConstants.ERROR_DATA_ISSUE + + " improper JSON object : " + jsonString; + LOGGER.error(message + e); + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ListConfigService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ListConfigService.java new file mode 100644 index 000000000..26f491963 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ListConfigService.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Collection; + +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java new file mode 100644 index 000000000..22d8873d7 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * MicroServices Policy implementation. + * + * @version 0.1 + */ +public class MicroServicesPolicyService{ + private static final Logger LOGGER = FlexLogger.getLogger(MicroServicesPolicyService.class.getName()); + + private 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 onapName = null; + private JsonObject microServiceAttributes = null; + + 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(); + LOGGER.error("Error while parsing JSON body for MicroService Policy creation. ", e); + return false; + } + onapName = policyParameters.getOnapName(); + if (onapName==null||onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + return false; + } + boolean levelCheck = 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 = null; + String policyDescription=null; + String priority=null; + String version=null; + if (microServiceAttributes.get("service")!=null){ + 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("\"", ""); + } + if(microServiceAttributes.containsKey("description")){ + policyDescription = microServiceAttributes.get("description").toString().replace("\"", ""); + } + if(microServiceAttributes.containsKey("priority")){ + priority = microServiceAttributes.get("priority").toString().replace("\"", ""); + } + if(microServiceAttributes.containsKey("version")){ + version = microServiceAttributes.get("version").toString().replace("\"", ""); + } + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Micro Service", policyName, policyDescription, onapName, + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java new file mode 100644 index 000000000..c1b9f63e1 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.utils.BusPublisher; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +import com.att.research.xacml.util.XACMLProperties; + +public class NotificationService { + public static final String BACKUPFILE = "topicBackup.txt"; + private static Logger logger = FlexLogger.getLogger(GetDictionaryService.class.getName()); + private static ConcurrentHashMap<String, Date> topicQueue = new ConcurrentHashMap<>(); + private static int interval = 15000; + private static Thread backUpthread = null; + private static Object resourceLock = new Object(); + private static List<String> dmaapList = null; + private static String dmaapServers = null; + private static String aafLogin = null; + private static String aafPassword = null; + + private String notificationResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + /** + * NotificationService Constructor. + * + * @param notificationTopic Topic Name in String format. + * @param requestID Request ID in String format. + * @param serviceType Needs to be NotificationServiceType based enumeration value. + */ + public NotificationService(String notificationTopic, String requestID, NotificationServiceType serviceType) { + init(); + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + notificationResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file"; + return; + } + 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(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + logger.info("Generated Random UUID: " + requestUUID.toString()); + } + try{ + run(notificationTopic, serviceType); + }catch(PolicyException e){ + notificationResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private static void init() { + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); + aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); + interval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY, Integer.toString(interval))); + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + return; + } + // Cleanup Values. + dmaapServers= dmaapServers.trim(); + aafLogin = aafLogin.trim(); + aafPassword = aafPassword.trim(); + // Get servers to List. + if(dmaapServers.contains(",")) { + dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); + } else { + dmaapList = new ArrayList<>(); + dmaapList.add(dmaapServers); + } + callThread(); + } + } + + private void run(String notificationTopic, NotificationServiceType serviceType) throws PolicyException{ + // Check Validation + if(notificationTopic==null){ + String message = "Notification Topic is null"; + logger.error(message); + throw new PolicyException(message); + } + notificationTopic = notificationTopic.trim(); + if(notificationTopic.isEmpty()){ + String message = "Notification Topic is not valid. "; + logger.error(message); + throw new PolicyException(message); + } + // if already exists give error.Saying already registered. + // Get Result. + try{ + status = HttpStatus.OK; + switch (serviceType) { + case ADD: + addTopic(notificationTopic); + notificationResponse = "Success!! Please give permissions to " + aafLogin + " that PDP will use to publish on given topic :" + notificationTopic + + "\n Start calling /sendHeartbeat API at an interval less than " + Integer.toString(interval) + "ms"; + break; + case REMOVE: + removeTopic(notificationTopic); + notificationResponse = "Notification Topic :" + notificationTopic + " has been removed and PDP will not publish notifications to this Topic."; + break; + case HB: + heartBeat(notificationTopic); + notificationResponse = "Success!! HeartBeat registered."; + break; + } + }catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + // Used to register Heart beat. + private void heartBeat(String notificationTopic) throws PolicyException{ + if(!topicQueue.isEmpty()&& topicQueue.containsKey(notificationTopic)){ + topicQueue.put(notificationTopic, new Date()); + }else{ + logger.info("Failed HeartBeat, Topic " + notificationTopic + "is not registered."); + throw new PolicyException("Failed HeartBeat, Topic " + notificationTopic + "is not registered."); + } + } + + // Used to remove Topic. + private static void removeTopic(String notificationTopic) throws PolicyException{ + if(topicQueue.containsKey(notificationTopic)){ + topicQueue.remove(notificationTopic); + removeTopicFromBackup(notificationTopic); + }else{ + logger.info("Failed Removal, Topic " + notificationTopic + " is not registered."); + throw new PolicyException("Failed Removal, Topic " + notificationTopic + " is not registered."); + } + } + + private static void removeTopicFromBackup(String notificationTopic) { + synchronized (resourceLock) { + try (Stream<String> lines = Files.lines(Paths.get(BACKUPFILE))) { + List<String> replaced = lines.map(line-> (line.split("=")[0].equals(notificationTopic)?"":line)).collect(Collectors.toList()); + try (PrintWriter pw = new PrintWriter( BACKUPFILE, "UTF-8")) { + replaced.forEach(line-> { + if(line.trim().isEmpty()){ + return; + } + pw.println(line); + }); + } + lines.close(); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not remove/recreate the backup. ", e); + } + } + } + + // Used to add Topic. + private void addTopic(String notificationTopic) throws PolicyException{ + // validate if topic exists. + if(!topicQueue.isEmpty()&& topicQueue.containsKey(notificationTopic)){ + topicQueue.put(notificationTopic, new Date()); + logger.info("Topic " + notificationTopic + " is already registered."); + throw new PolicyException("Topic " + notificationTopic + " is already registered."); + } + topicQueue.put(notificationTopic, new Date()); + addTopictoBackUp(notificationTopic); + } + + private void addTopictoBackUp(String notificationTopic) { + synchronized (resourceLock) { + try { + Files.write(Paths.get(BACKUPFILE),( notificationTopic+"="+new Date().toString()+"\n").getBytes() , StandardOpenOption.APPEND); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not add to the backup. ", e); + } + } + } + + // Maintains BackUp and Queue Topic. + private static void callThread() { + // Create the backup file if it not exists. + backup(); + if(backUpthread==null){ + Runnable task = () -> { + logger.info("BackUpThread not set. Starting now !"); + threadTask(); + }; + backUpthread = new Thread(task); + backUpthread.start(); + } + } + + private static void backup(){ + synchronized (resourceLock) { + try{ + File backUpFile = new File(BACKUPFILE); + if(!backUpFile.exists() && backUpFile.createNewFile()){ + logger.info(" BackUp File for topic's has been created !"); + }else{ + // File Already exists. Process file and load the Memory. + Stream<String> stream = Files.lines(Paths.get(BACKUPFILE)); + Map<String,Date> data = stream.map(line -> line.split(",")).collect(Collectors.toMap(e->e[0],e-> new Date())); + stream.close(); + data.forEach((key, value)->logger.debug("Topic retrieved from backUp : " + key + " with Time : " + value)); + topicQueue.putAll(data); + } + }catch(IOException e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not process the backup. ", e); + } + } + } + + private static void threadTask() { + while(true){ + try { + TimeUnit.MILLISECONDS.sleep(interval); + for(Map.Entry<String, Date> map : topicQueue.entrySet()){ + Date currentTime = new Date(); + long timeDiff = 0; + timeDiff = currentTime.getTime()-map.getValue().getTime(); + if(timeDiff < (interval+1500)){ + removeTopic(map.getKey()); + } + } + } catch (InterruptedException | PolicyException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error during thread execution ", e); + } + } + } + + public String getResult() { + return notificationResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + + /** + * Entry point for sending Notifications from Notification Server. + * @param notification String JSON format of notification message which needs to be sent. + */ + public static void sendNotification(String notification) { + init(); + for (String topic: topicQueue.keySet()){ + sendDmaapMessage(topic, notification); + } + } + + private static void sendDmaapMessage(String topic, String notification) { + BusPublisher publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList, + topic, + aafLogin, + aafPassword); + // Sending notification through DMaaP Message Router + publisher.send( "MyPartitionKey", notification); + logger.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic); + publisher.close(); + } + + /** + * Notification service Type Enumeration + */ + public enum NotificationServiceType{ + ADD, + REMOVE, + HB + } + +}
\ No newline at end of file diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java new file mode 100644 index 000000000..e7216e152 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java @@ -0,0 +1,656 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.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.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.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.config.PDPApiAuth; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.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: ---"); + if(connection != null){ + 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; + } + }else{ + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null"; + } + 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() + e); + } + }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); + connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); + + //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() + e1); + } + } + + } 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() + e); + } + } + } + return version; + } + + 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 + + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " + + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + " that already exists." + " See detailed information on ClosedLoop Pairs below: " + +"\n\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 + + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " + + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + " that already exists. " + "See detailed information on ClosedLoop Pairs below: " + +"\n\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() + e1); + } + 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."; + } else if("PolicyInPDP".equals(connection.getHeaderField("error"))){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Policy Exist Error: The Policy trying to be deleted is active in PDP. " + + "Active PDP Polcies are not allowed to be deleted from PAP. " + + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP."; + } + 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 ("validation".equals(connection.getHeaderField("error"))){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Validation errors during policy engine " + connection.getHeaderField("operation") + + " for " + connection.getHeaderField("service"); + } else if ("error".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_UNKNOWN + + "Could not create or update the policy for and unknown reason"; + }else{ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect. " + connection.getHeaderField("error"); + } + 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+"onap/pushPolicy" : fullURL+"/onap/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: ---"); + if(connection != null){ + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java new file mode 100644 index 000000000..e495c9950 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java @@ -0,0 +1,439 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.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.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyDecision; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.api.PolicyType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.XACMLPdpServlet; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.std.Matches; +import org.onap.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 final 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 Request rainydayRequest = 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); + // Assign a rainy day treatment request to parse the decided treatment + if (jsonString.contains("BB_ID")) { + rainydayRequest = request; + } + // Call the PDP + LOGGER.info("--- 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.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.info("No Response Received from PDP"); + PDPResponse pdpResponse = new PDPResponse(); + results = new HashSet<>(); + 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<>(); + int priority = DEFAULT_PRIORITY; + Map<Integer, PDPResponse> uniqueResult = new HashMap<>(); + for (Result result : response.getResults()) { + if (!result.getDecision().equals(Decision.PERMIT)) { + LOGGER.info("Decision not a Permit. " + result.getDecision().toString()); + PDPResponse pdpResponse = new PDPResponse(); + if (decide) { + String indeterminatePropValue = XACMLProperties.getProperty("decision.inStringdeterminate.response"); + if(result.getDecision().equals(Decision.INDETERMINATE)&& indeterminatePropValue != null){ + if("PERMIT".equalsIgnoreCase(indeterminatePropValue)){ + pdpResponse.setDecision(PolicyDecision.PERMIT); + }else{ + pdpResponse.setDecision(PolicyDecision.DENY); + } + }else{ + 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); + + //if this is a Rainy Day treatment decision we need to get the selected treatment + if(rainydayRequest!=null){ + pdpResponse.setDetails(getRainyDayTreatment(result)); + } else { + 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; + Matches match = new Matches(); + Map<String, String> matchingConditions = new HashMap<>(); + Map<String, String> configAttributes = new HashMap<>(); + Map<String, String> responseAttributes = new HashMap<>(); + Map<String, String> actionTaken = new HashMap<>(); + PDPResponse pdpResponse = new PDPResponse(); + Map<String, String> adviseAttributes = new HashMap<>(); + for (AttributeAssignment attribute : advice.getAttributeAssignments()) { + adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); + if ("CONFIGURATION".equalsIgnoreCase(attribute.getAttributeValue().getValue().toString())) { + 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 (!("PDP".equalsIgnoreCase(attribute.getIssuer()))) { + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy"); + } + } + } else if ("PolicyName".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { + policyName = attribute.getAttributeValue().getValue().toString(); + } else if ("VersionNumber".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { + policyVersion = attribute.getAttributeValue().getValue().toString(); + } else if ("Priority".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ + 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",e); + priority = DEFAULT_PRIORITY; + } + } else if (attribute.getAttributeId().stringValue().startsWith("matching")) { + matchingConditions.put(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); + if ("ONAPName".equals(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""))) { + match.setOnapName(attribute.getAttributeValue().getValue().toString()); + } else if ("ConfigName".equals(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""))) { + 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<>(); + 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 String getRainyDayTreatment(Result result) { + String treatment = null; + if (rainydayRequest!=null&& !result.getAssociatedAdvice().isEmpty()) { + // Get the desired treatment for requested errorCode from the Advice + for (Advice advice : result.getAssociatedAdvice()) { + Map<String, String> adviseAttributes = new HashMap<>(); + for (AttributeAssignment attribute : advice.getAttributeAssignments()) { + adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); + if ("treatment".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ + treatment = attribute.getAttributeValue().getValue().toString(); + } + } + } + } + return treatment; + } + + private PDPResponse configCall(String pdpConfigLocation) throws Exception{ + PDPResponse pdpResponse = new PDPResponse(); + if(pdpConfigLocation.contains("/")){ + pdpConfigLocation = pdpConfigLocation.replace("/", File.separator); + } + InputStream inputStream = null; + try { + 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<>(); + 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); + }finally{ + if(inputStream != null){ + inputStream.close(); + } + } + } + + 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.info("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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java new file mode 100644 index 000000000..2d8af54c5 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java @@ -0,0 +1,186 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; + +import org.onap.policy.api.ImportParameters; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.ImportParameters.IMPORT_TYPE; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.utils.PolicyUtils; +import org.onap.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==null || importResponse.contains("PE200")){ + status = HttpStatus.INTERNAL_SERVER_ERROR; + }else if(importResponse.contains("BAD REQUEST") || importResponse.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; + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PushPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PushPolicyService.java new file mode 100644 index 000000000..f2c6c221c --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PushPolicyService.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.UUID; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; +import org.onap.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 final 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(), e); + } + }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; + } + 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/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/SendEventService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/SendEventService.java new file mode 100644 index 000000000..c655a2ad4 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/SendEventService.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-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.onap.policy.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.onap.policy.api.EventRequestParameters; +import org.onap.policy.api.PolicyEventException; +import org.onap.policy.api.PolicyResponse; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.std.StdPolicyResponse; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class SendEventService { + private static final 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(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.eventRequestParameters.setRequestID(requestUUID); + } + policyResponses = new ArrayList<>(); + 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<>(); + if (generateRequest == null) { + return result; + } + 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 (Entry<String,String> key : eventAttributes.entrySet()) { + if (key.getKey().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(message); + throw new PolicyEventException(message); + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (key.getValue().matches("[0-9]+")) { + int val = Integer.parseInt(key.getValue()); + resourceBuilder.add("Value", val); + } else { + resourceBuilder.add("Value", key.getValue()); + } + resourceBuilder.add("AttributeId", key.getKey()); + resourceArray.add(resourceBuilder); + } + return Json.createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("Resource",Json.createObjectBuilder() + .add("Attribute",resourceArray))) + .build(); + } + + 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; + } + +} |