From 91d04c64771832a0b8815ffbe1f0f9920320d94d Mon Sep 17 00:00:00 2001 From: Pamela Dragosh Date: Tue, 14 Feb 2017 19:41:00 -0500 Subject: Initial OpenECOMP policy/engine commit Change-Id: I7dbff37733b661643dd4d1caefa3d7dccc361b6e Signed-off-by: Pamela Dragosh --- .../openecomp/policyEngine/ActionPolicyClient.java | 117 ++++++ .../policyEngine/BrmsParamPolicyClient.java | 107 ++++++ .../policyEngine/BrmsRawPolicyClient.java | 144 ++++++++ .../policyEngine/ClosedLoopPolicyClient.java | 119 ++++++ .../ClosedLoopPolicyPerformanceMetricClient.java | 121 +++++++ .../policyEngine/ConfigBasePolicyClient.java | 92 +++++ .../policyEngine/ConfigFirewallPolicyClient.java | 117 ++++++ .../policyEngine/DecisionPolicyClient.java | 116 ++++++ .../openecomp/policyEngine/DeletePolicyClient.java | 62 ++++ .../openecomp/policyEngine/GeneralTestClient.java | 398 +++++++++++++++++++++ .../openecomp/policyEngine/GetConfigSample.java | 41 +++ .../java/org/openecomp/policyEngine/Handler.java | 121 +++++++ .../policyEngine/ImportMicroServiceClient.java | 56 +++ .../policyEngine/ListConfigPoliciesClient.java | 83 +++++ .../org/openecomp/policyEngine/MainClient.java | 162 +++++++++ .../policyEngine/MicroServicesPolicyClient.java | 121 +++++++ .../policyEngine/PolicyEngineTestClient.java | 201 +++++++++++ .../openecomp/policyEngine/PushPoliciesToPDP.java | 59 +++ 18 files changed, 2237 insertions(+) create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ActionPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsParamPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsRawPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigBasePolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DecisionPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DeletePolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GeneralTestClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GetConfigSample.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/Handler.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ImportMicroServiceClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ListConfigPoliciesClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MainClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PolicyEngineTestClient.java create mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PushPoliciesToPDP.java (limited to 'PolicyEngineClient/src/main/java/org') diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ActionPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ActionPolicyClient.java new file mode 100644 index 000000000..4ecc488c5 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ActionPolicyClient.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyClass; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; + +public class ActionPolicyClient { + static Boolean isEdit = true; + public static void main(String[] args) { + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + // Set Policy Type + policyParameters.setPolicyClass(PolicyClass.Action); //required + policyParameters.setPolicyName("MikeAPItesting.testActionAPI5"); //required + policyParameters.setPolicyDescription("This is a sample Action policy update example with no Action Body"); //optional + //policyParameters.setPolicyScope("MikeAPItesting"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + + //Set the Component Attributes... These are Optional + Map configAttributes = new HashMap(); + configAttributes.put("Template", "UpdateTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + + Map> attributes = new HashMap>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + + //Set the Rule Algorithm + // Map>> translated to Map>> + Map>> ruleAlgorithm = new HashMap>>(); + + List dynamicRuleAlgorithmLabels = new LinkedList(); + List dynamicRuleAlgorithmFunctions = new LinkedList(); + List dynamicRuleAlgorithmField1 = new LinkedList(); + List dynamicRuleAlgorithmField2 = new LinkedList(); + + //Example of a complex Rule algorithm + /* label field1 function field2 + * ***************************************************** + * A1 cobal integer-equal 90 + * A2 cap string-contains ca + * A3 cobal integer-equal 90 + * A4 A2 and A3 + * A5 Config integer-greater-than 45 + * A6 A4 ` or A5 + * A7 A1 and A6 + */ + dynamicRuleAlgorithmLabels = Arrays.asList("A1","A2","A3","A4","A5","A6","A7"); + dynamicRuleAlgorithmField1 = Arrays.asList("cobal","cap","cobal","A2","Config","A4","A1"); + dynamicRuleAlgorithmFunctions = Arrays.asList("integer-equal","string-contains","integer-equal","and","integer-greater-than","or","and"); + dynamicRuleAlgorithmField2 = Arrays.asList("90","ca","90","A3","45","A5","A6"); + + policyParameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyParameters.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyParameters.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions); + policyParameters.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + + policyParameters.setActionPerformer("PEP"); + policyParameters.setActionAttribute("mikeTest2"); + policyParameters.setRequestID(UUID.randomUUID()); + + // API method to create Policy or update policy + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } else { + response = policyEngine.updatePolicy(policyParameters); + } + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } + +} + + diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsParamPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsParamPolicyClient.java new file mode 100644 index 000000000..3d80fe2ef --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsParamPolicyClient.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; + + +public class BrmsParamPolicyClient { + + public static void main(String[] args) { + try { + + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + + PolicyParameters policyParameters = new PolicyParameters(); + + // Set Policy Type(Mandatory) + policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + + // Set Policy Name(Mandatory) + policyParameters.setPolicyName("Lakshman.testParamPolicyThree"); + + // Set Safe Policy value for Risk Type + SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy"); + Date date = dateformat3.parse("15/10/2016"); + policyParameters.setTtlDate(date); + // Set Safe Policy value for Guard + policyParameters.setGuard(true); + // Set Safe Policy value for Risk Level + policyParameters.setRiskLevel("5"); + // Set Safe Policy value for Risk Type + policyParameters.setRiskType("PROD"); + + // Set description of the policy(Optional) + policyParameters.setPolicyDescription("This is a sample BRMS Param policy creation example"); + + //Set Scope folder where the policy needs to be created(Mandatory) + //policyParameters.setPolicyScope("Lakshman"); + + // Set BRMS Param Template Attributes(Mandatory) + Map ruleAttributes = new HashMap(); + ruleAttributes.put("templateName", "Sample"); // This sampleTemplate is the Template name from dictionary. + ruleAttributes.put("controller", "default"); // Set Rule to a PDP Controller, default is the controller name. + ruleAttributes.put("SamPoll", "300"); // Template specific key and value set by us. + ruleAttributes.put("value", "abcd"); // Template specific key and value set by us. + Map> attributes = new HashMap>(); + attributes.put(AttributeType.RULE, ruleAttributes); + policyParameters.setAttributes(attributes); + + //Set a random UUID(Mandatory) + policyParameters.setRequestID(UUID.randomUUID()); + + // CreatePolicy method to create Policy. + + PolicyChangeResponse response = policyEngine.updatePolicy(policyParameters); + + if(response.getResponseCode()==200){ + + System.out.println(response.getResponseMessage()); + + System.out.println("Policy Created Successfully!"); + + }else{ + + System.out.println("Error! " + response.getResponseMessage()); + + } + + } catch (Exception e) { + + System.err.println(e.getMessage()); + + } + + } + +} + + diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsRawPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsRawPolicyClient.java new file mode 100644 index 000000000..a8601c1cb --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsRawPolicyClient.java @@ -0,0 +1,144 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyClass; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; + +public class BrmsRawPolicyClient { + static Boolean isEdit = true; + + //Reads a File and converts into a String. + private static String readFile( String file ) throws IOException { + BufferedReader reader = new BufferedReader( new FileReader (file)); + String line = null; + StringBuilder stringBuilder = new StringBuilder(); + String ls = System.getProperty("line.separator"); + + try { + while( ( line = reader.readLine() ) != null ) { + stringBuilder.append( line ); + stringBuilder.append( ls ); + } + + return stringBuilder.toString(); + } finally { + reader.close(); + } + } + + + public static void main(String[] args) { + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + Map attrib= new HashMap(); + attrib.put("cpu","80"); + attrib.put("memory", "50"); + Map> attributes = new HashMap>(); + attributes.put(AttributeType.RULE, attrib); + + // Set Policy Type + policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_RAW); //required + policyParameters.setPolicyName("Lakshman.testBRMSRawAPITwo"); //required + policyParameters.setPolicyDescription("This is a sample BRMS Raw policy body"); //optional + policyParameters.setAttributes(attributes); + //policyParameters.setPolicyScope("Lakshman"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + policyParameters.setRequestID(UUID.randomUUID()); + + // Set Safe Policy value for Risk Type + SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy"); + Date date = dateformat3.parse("15/10/2016"); + policyParameters.setTtlDate(date); + // Set Safe Policy value for Guard + policyParameters.setGuard(true); + // Set Safe Policy value for Risk Level + policyParameters.setRiskLevel("5"); + // Set Safe Policy value for Risk Type + policyParameters.setRiskType("PROD"); + + File rawBodyFile = null; + + Path file = Paths.get("C:\\Users\\testuser\\Documents\\API\\com.Config_BRMS_Raw_TestBrmsPolicy.1.txt"); + rawBodyFile = file.toFile(); + + policyParameters.setConfigBody(readFile(rawBodyFile.toString())); + policyParameters.setConfigBodyType(PolicyType.OTHER); + + /*public String createUpdateBRMSRawPolicy(String policyName, + String policyDescription, + Map dyanamicFieldConfigAttributes, + String brmsRawBody, + String policyScope, + Boolean isEdit, + UUID requestID) */ + + // API method to create Policy or update policy + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } else { + response = policyEngine.updatePolicy(policyParameters); + } + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } + +} + + diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java new file mode 100644 index 000000000..4f0926cca --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; + +public class ClosedLoopPolicyClient { + //For updating a ClosedLoop_Fault policy set the "isEdit" flag to true. + //For creating a ClosedLoop_Fault policy set the "isEdit" flag to false. + static Boolean isEdit = false; + + //Builds JSONObject from File + private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException { + JsonObject json = null;; + + if (jsonString != null && jsonInput == null) { + StringReader in = null; + in = new StringReader(jsonString); + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + else { + InputStream in = null; + in = new FileInputStream(jsonInput); + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + + return json; + } + public static void main(String[] args) { + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + // Set Policy Type + policyParameters.setPolicyConfigType(PolicyConfigType.ClosedLoop_Fault); + policyParameters.setPolicyName("MikeAPItests.ClosedLoopFaultApiTest45"); + policyParameters.setPolicyDescription("This is a sample ClosedLoop_Fault policy CREATE example"); + //policyParameters.setPolicyScope("MikeAPItests"); + + // Set up Micro Services Attributes + File jsonFile = null; + String MSjsonString= null; + if (MSjsonString == null) { + Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\faultTestJson.json"); + jsonFile = file.toFile(); + } + policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString()); + policyParameters.setConfigBodyType(PolicyType.JSON); + + policyParameters.setRequestID(UUID.randomUUID()); + // Set Safe Policy value for Risk Type + SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy"); + Date date = dateformat3.parse("15/10/2016"); + policyParameters.setTtlDate(date); + // Set Safe Policy value for Guard + policyParameters.setGuard(true); + // Set Safe Policy value for Risk Level + policyParameters.setRiskLevel("5"); + // Set Safe Policy value for Risk Type + policyParameters.setRiskType("PROD"); + + // API method to create or update Policy. + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } + else { + response = policyEngine.updatePolicy(policyParameters); + } + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java new file mode 100644 index 000000000..6357cea5a --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; + +public class ClosedLoopPolicyPerformanceMetricClient { + + //For updating a ClosedLoop_Fault policy set the "isEdit" flag to true. + //For creating a ClosedLoop_Fault policy set the "isEdit" flag to false. + static Boolean isEdit = true; + + //Builds JSONObject from File + private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException { + JsonObject json = null;; + + if (jsonString != null && jsonInput == null) { + StringReader in = null; + in = new StringReader(jsonString); + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + else { + InputStream in = null; + in = new FileInputStream(jsonInput); + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + + return json; + } + + public static void main(String[] args) { + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + // Set Policy Type + policyParameters.setPolicyConfigType(PolicyConfigType.ClosedLoop_PM); + policyParameters.setPolicyName("MikeAPItests.ClosedLoopPmApiTest"); + policyParameters.setPolicyDescription("This is a sample ClosedLoop_PM policy CREATE example"); + //policyParameters.setPolicyScope("MikeAPItests"); + + // Set up Micro Services Attributes + File jsonFile = null; + String MSjsonString= null; + if (MSjsonString == null) { + Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\pmTestJson.json"); + jsonFile = file.toFile(); + } + policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString()); + policyParameters.setConfigBodyType(PolicyType.JSON); + + policyParameters.setRequestID(UUID.randomUUID()); + // Set Safe Policy value for Risk Type + SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy"); + Date date = dateformat3.parse("15/10/2016"); + policyParameters.setTtlDate(date); + // Set Safe Policy value for Guard + policyParameters.setGuard(true); + // Set Safe Policy value for Risk Level + policyParameters.setRiskLevel("5"); + // Set Safe Policy value for Risk Type + policyParameters.setRiskType("PROD"); + + // API method to create or update Policy. + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } + else { + response = policyEngine.updatePolicy(policyParameters); + } + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigBasePolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigBasePolicyClient.java new file mode 100644 index 000000000..dcaaaf188 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigBasePolicyClient.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; + +public class ConfigBasePolicyClient{ + static Boolean isEdit = false; + public static void main(String[] args) { + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + // Set Policy Type + policyParameters.setPolicyConfigType(PolicyConfigType.Base); //required + policyParameters.setPolicyName("MikeConsole.testDeleteAPI6"); //required + policyParameters.setPolicyDescription("This is a sample Config Base policy creation example"); //optional + policyParameters.setEcompName("DCAE"); //required + policyParameters.setConfigName("testBase"); //required + policyParameters.setConfigBodyType(PolicyType.OTHER); //required + policyParameters.setConfigBody("testing"); //required + //policyParameters.setPolicyScope("MikeConsole"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + + //Set the Config Attributes... These are Optional + Map configAttributes = new HashMap(); + configAttributes.put("Template", "SampleTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + Map> attributes = new HashMap>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + policyParameters.setRequestID(UUID.randomUUID()); + // Set Safe Policy value for Risk Type + SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy"); + Date date = dateformat3.parse("15/10/2016"); + policyParameters.setTtlDate(date); + // Set Safe Policy value for Guard + policyParameters.setGuard(true); + // Set Safe Policy value for Risk Level + policyParameters.setRiskLevel("5"); + // Set Safe Policy value for Risk Type + policyParameters.setRiskType("PROD"); + + // API method to create Policy or update policy + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } else { + response = policyEngine.updatePolicy(policyParameters); + } + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } + +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java new file mode 100644 index 000000000..5c6752bd5 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; + +public class ConfigFirewallPolicyClient { + static Boolean isEdit = false; + public static void main(String[] args) { + try{ + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + // Set Policy Type + policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); //required + policyParameters.setPolicyName("MikeAPItesting.testConfigFirewallPolicy1607_1"); //required + //policyParameters.setPolicyScope("MikeAPItesting"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + policyParameters.setRequestID(UUID.randomUUID()); + + // Set Safe Policy value for Risk Type + SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy"); + Date date = dateformat3.parse("15/10/2016"); + policyParameters.setTtlDate(date); + // Set Safe Policy value for Guard + policyParameters.setGuard(true); + // Set Safe Policy value for Risk Level + policyParameters.setRiskLevel("5"); + // Set Safe Policy value for Risk Type + policyParameters.setRiskType("PROD"); + File jsonFile = null; + String jsonRuleList = null; + if (jsonRuleList == null) { + Path file = Paths.get("C:\\policyAPI\\firewallRulesJSON\\Config_FW_1607Rule.json"); + jsonFile = file.toFile(); + } + //buildJSON(jsonFile, jsonRuleList); + policyParameters.setConfigBody(buildJSON(jsonFile, jsonRuleList).toString()); + policyParameters.setConfigBodyType(PolicyType.JSON); + // API method to create Policy or update policy + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } else { + response = policyEngine.updatePolicy(policyParameters); + } + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + +} + + private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException { + JsonObject json = null;; + if (jsonString != null && jsonInput == null) { + StringReader in = null; + + in = new StringReader(jsonString); + + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + + + } else { + InputStream in = null; + in = new FileInputStream(jsonInput); + + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + + return json; + } + +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DecisionPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DecisionPolicyClient.java new file mode 100644 index 000000000..1c446fdca --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DecisionPolicyClient.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyClass; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; + +public class DecisionPolicyClient { + static Boolean isEdit = true; + public static void main(String[] args) { + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + // Set Policy Type + policyParameters.setPolicyClass(PolicyClass.Decision); //required + policyParameters.setPolicyName("MikeAPItests.testDecisionAPI"); //required + policyParameters.setEcompName("java"); //required + policyParameters.setPolicyDescription("This is a sample Decision policy UPDATE example with Settings"); //optional + //policyParameters.setPolicyScope("MikeAPItests"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + + //Set the Component Attributes... These are Optional + Map configAttributes = new HashMap(); + configAttributes.put("Template", "UpdateTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + + Map> attributes = new HashMap>(); + attributes.put(AttributeType.MATCHING, configAttributes); + + //Set the settings... These are Optional + Map settingsMap = new HashMap(); + settingsMap.put("server", "5"); + + attributes.put(AttributeType.SETTINGS, settingsMap); + policyParameters.setAttributes(attributes); + + //Set the Rule Algorithm... These are Optional + Map>> ruleAlgorithm = new HashMap>>(); + + List dynamicRuleAlgorithmLabels = new LinkedList(); + List dynamicRuleAlgorithmFunctions = new LinkedList(); + List dynamicRuleAlgorithmField1 = new LinkedList(); + List dynamicRuleAlgorithmField2 = new LinkedList(); + + //Example of a complex Rule algorithm using the settings in the Field1 + /* label field1 function field2 + * ***************************************************** + * A1 S_server integer-equal 90 + * A2 cap string-contains ca + * A3 cobal integer-equal 90 + * A4 A2 and A3 + * A5 Config integer-greater-than 45 + * A6 A4 ` or A5 + * A7 A1 and A6 + */ + dynamicRuleAlgorithmLabels = Arrays.asList("A1","A2","A3","A4","A5","A6","A7"); + dynamicRuleAlgorithmField1 = Arrays.asList("S_server","cap","cobal","A2","Config","A4","A1"); + dynamicRuleAlgorithmFunctions = Arrays.asList("integer-equal","string-contains","integer-equal","and","integer-greater-than","or","and"); + dynamicRuleAlgorithmField2 = Arrays.asList("90","ca","90","A3","45","A5","A6"); + + policyParameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyParameters.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyParameters.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions); + policyParameters.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + + policyParameters.setRequestID(UUID.randomUUID()); + + // API method to create Policy or update policy + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } else { + response = policyEngine.updatePolicy(policyParameters); + } + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } + +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DeletePolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DeletePolicyClient.java new file mode 100644 index 000000000..79ec99f85 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DeletePolicyClient.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import org.openecomp.policy.api.DeletePolicyCondition; +import org.openecomp.policy.api.DeletePolicyParameters; +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyEngine; + +public class DeletePolicyClient { + + public static void main(String[] args) { + try { + + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + DeletePolicyParameters policyParameters = new DeletePolicyParameters(); + + //Parameter arguments + policyParameters.setPolicyName("MikeConsole.Config_testDeleteAPI6.1.xml"); + policyParameters.setPolicyComponent("PDP"); + policyParameters.setPdpGroup("default"); + policyParameters.setDeleteCondition(DeletePolicyCondition.ALL); + policyParameters.setRequestID(null); + + // API method to Push Policy to PDP + PolicyChangeResponse response = null; + response = policyEngine.deletePolicy(policyParameters); + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Deleted Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + + } catch (Exception e) { + System.err.println(e.getMessage()); + + } + + } + + +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GeneralTestClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GeneralTestClient.java new file mode 100644 index 000000000..c78fc6f11 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GeneralTestClient.java @@ -0,0 +1,398 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * 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========================================================= + */ + +/* + * AT&T - PROPRIETARY + * THIS FILE CONTAINS PROPRIETARY INFORMATION OF + * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN + * ACCORDANCE WITH APPLICABLE AGREEMENTS. + * + * Copyright (c) 2014 AT&T Knowledge Ventures + * Unpublished and Not for Publication + * All Rights Reserved + */ +package org.openecomp.policyEngine; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyEngineException; + +/** + * Class reads from .testCases file and run the test cases available in the file + * and generates output for each test cases specifing whether is passed or fail + * and reason why it fails. + * + * + * @version 1.0 + * + */ +public class GeneralTestClient { + static int totalTC = 0, passTC = 0, failTC = 0; + + public static void main(String[] args) { + Path file; + /* command line arguments */ + if (args.length != 0) { + for (int index = 0; index < args.length; index++) { + // System.out.println(args[index]); + file = Paths.get(args[index]); + runTestClientOnConfigFile(file); + } + } else { + /* default file */ + file = Paths.get("input.testCases"); + runTestClientOnConfigFile(file); + } + System.out + .println("###############################################################################################"); + System.out.println("\n\t SUMMARY: TOTAL: " + totalTC + ",\tPASS: " + + passTC + ",\tFAIL: " + failTC + "\n"); + System.out + .println("###############################################################################################"); + + System.out.println("Enter a any key to exit"); + try { + System.in.read(); + } catch (IOException e) { + // + } + + } + + /** + * This function reads the files passed as arguments and runs the test cases + * in the file + * + * @param file + */ + private static void runTestClientOnConfigFile(Path file) { + String resultReturned, eCOMPComponentName; + int totalTCforFile = 0, passTCforFile = 0, failTCforFile = 0; + System.out + .println("\n###############################################################################################"); + System.out.println("\tRuning test Client on Config file: " + file); + System.out + .println("###############################################################################################\n"); + + if (Files.notExists(file)) { + System.out.println("file doesnot exist"); + // throw new + // PolicyEngineException("File doesn't exist in the specified Path " + // + file.toString()); + } else if (file.toString().endsWith(".testCases")) { + try { + // read the json file + FileReader reader = new FileReader(file.toString()); + + JSONParser jsonParser = new JSONParser(); + JSONArray jsonObjectArray = (JSONArray) jsonParser + .parse(reader); + for (Object jsonObject : jsonObjectArray) { + totalTC++; + totalTCforFile++; + ArrayList expectedResult = new ArrayList(); + ArrayList resultReceived = new ArrayList(); + JSONObject testCase = (JSONObject) jsonObject; + // get a String from the JSON object + long id = (long) testCase.get("id"); + String testFor = (String) testCase.get("testFor"); + String testCaseDescription = (String) testCase + .get("testCaseDescription"); + JSONArray expectedResultJson = (JSONArray) testCase + .get("expectedResult"); + @SuppressWarnings("rawtypes") + Iterator i = expectedResultJson.iterator(); + while (i.hasNext()) { + expectedResult.add((String) i.next()); + } + String pdp_urlConfigFile = (String) testCase + .get("PDP_URLConfigFile"); + // System.out.println(pdp_urlConfigFile); + PolicyEngine policyEngine; + try { + policyEngine = new PolicyEngine(pdp_urlConfigFile); + + switch (testFor) { + + case "getConfig": + eCOMPComponentName = (String) testCase + .get("ECOMPName"); + String configName = (String) testCase + .get("ConfigName"); + Map configAttributes = new HashMap(); + configAttributes.put("key", "value"); + JSONArray configAttributesJSON = (JSONArray) testCase + .get("configAttributes"); + if(configAttributesJSON!=null){ + i = configAttributesJSON.iterator(); + while (i.hasNext()) { + JSONObject innerObj = (JSONObject) i.next(); + configAttributes.put( + (String) innerObj.get("key"), + (String) innerObj.get("value")); + + } + }else{ + configAttributes = null; + } + resultReceived = PolicyEngineTestClient.getConfig( + policyEngine, eCOMPComponentName, + configName, configAttributes); + Collections.sort(expectedResult); + Collections.sort(resultReceived); + resultReturned = compareResults(expectedResult,resultReceived); + if (resultReturned.equals("PASSED")) { + printResult(id, testFor, testCaseDescription, + "PASSED"); + passTCforFile++; + passTC++; + } else { + printResult(id, testFor, testCaseDescription, + "FAILED", resultReturned); + failTCforFile++; + failTC++; + } + break; + + case "getAction": + Map eventAttributes = new HashMap(); + eventAttributes.put("Key", "Value"); + JSONArray eventAttributesJSON = (JSONArray) testCase + .get("eventAttributes"); + if(eventAttributesJSON != null){ + i = eventAttributesJSON.iterator(); + while (i.hasNext()) { + JSONObject innerObj = (JSONObject) i.next(); + eventAttributes.put( + (String) innerObj.get("key"), + (String) innerObj.get("value")); + } + }else{ + eventAttributes=null; + } + resultReceived = PolicyEngineTestClient.getAction( + policyEngine, eventAttributes); + Collections.sort(expectedResult); + Collections.sort(resultReceived); + resultReturned = compareResults(expectedResult, + resultReceived); + if (resultReturned.equals("PASSED")) { + printResult(id, testFor, testCaseDescription, + "PASSED"); + passTCforFile++; + passTC++; + } else { + printResult(id, testFor, testCaseDescription, + "FAILED", resultReturned); + failTCforFile++; + failTC++; + } + break; + + case "getDecision": + eCOMPComponentName = (String) testCase + .get("ECOMPName"); + Map decisionAttributes = new HashMap(); + decisionAttributes.put("Key", "Value"); + JSONArray decisionAttributesJSON = (JSONArray) testCase + .get("decisionAttributes"); + i = decisionAttributesJSON.iterator(); + while (i.hasNext()) { + JSONObject innerObj = (JSONObject) i.next(); + decisionAttributes.put( + (String) innerObj.get("key"), + (String) innerObj.get("value")); + + } + + resultReceived = PolicyEngineTestClient + .getDecision(policyEngine, + eCOMPComponentName, + decisionAttributes); + Collections.sort(expectedResult); + Collections.sort(resultReceived); + resultReturned = compareResults(expectedResult, + resultReceived); + if (resultReturned.equals("PASSED")) { + printResult(id, testFor, testCaseDescription, + "PASSED"); + passTCforFile++; + passTC++; + } else { + printResult(id, testFor, testCaseDescription, + "FAILED", resultReturned); + failTCforFile++; + failTC++; + } + break; + + // case "getManualNotification": + // PolicyEngineTestClient + // .getManualNotifications(org.openecomp.policyEngine); + // break; + // case "getAutoNotification": + // PolicyEngineTestClient + // .getAutoNotifications(org.openecomp.policyEngine); + // break; + + default: + printResult(id, testFor, testCaseDescription, + "FAILED", "\tINVAILD TEST CASE."); + failTCforFile++; + failTC++; + break; + + } + } catch (PolicyEngineException e) { + // TODO Auto-generated catch block + printResult(id, testFor, testCaseDescription, "FAILED"); + failTCforFile++; + failTC++; + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + printResult(id, testFor, testCaseDescription, "FAILED"); + failTCforFile++; + failTC++; + e.printStackTrace(); + } + } + + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); + } catch (NullPointerException ex) { + ex.printStackTrace(); + } catch (org.json.simple.parser.ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + System.out.println("\n\n\t Summary for the file: TOTAL: " + + totalTCforFile + ",\tPASS: " + passTCforFile + ",\tFAIL: " + + failTCforFile + "\n"); + } + + /** + * This function prints the reason if test fails. + * + * @param id + * @param testFor + * @param testCaseDescription + * @param passFail + * @param resultReturned + */ + private static void printResult(long id, String testFor, + String testCaseDescription, String passFail, String resultReturned) { + // TODO Auto-generated method stub + printResult(id, testFor, testCaseDescription, passFail); + System.out.println(resultReturned); + + } + + /** + * This function prints in output in required format. + * + * @param id + * @param testFor + * @param testCaseDescription + * @param result + */ + private static void printResult(long id, String testFor, + String testCaseDescription, String result) { + System.out.println(result + " - Test Case " + id + " - Test type: " + + testFor + " - " + testCaseDescription); + } + + /** + * This function compares the required expected output and received output + * and returns PASS if expected output and received output matches + * + * @param expectedResult + * @param resultReceived + * @return + */ + private static String compareResults(ArrayList expectedResult, + ArrayList resultReceived) { + // TODO Auto-generated method stub + String returnString = ""; + int index; +// System.out.println(expectedResult.size()); +// System.out.println(resultReceived.size()); + for (index = 0; index < expectedResult.size() + || index < resultReceived.size(); index++) { + if (index < expectedResult.size() && index < resultReceived.size()) { + if (!expectedResult.get(index) + .equals(resultReceived.get(index))) { + //returnString = "FAILED"; + returnString += "\tExpected Output: " + + expectedResult.get(index) + + ",\n\tOutput Received: " + + resultReceived.get(index)+"\n"; +// + //System.out.println(resultReceived.get(index)); + } + + } else { + if (index >= expectedResult.size()) { + returnString += "\tExpected Size of output: " + + expectedResult.size() + + ", Size of output received: " + + resultReceived.size() + + "\n\tExpected Output: none,\n\tOutput Received: " + + resultReceived.get(index)+"\n"; + + } else { + if (index >= resultReceived.size()) { + returnString += "\tExpected Size of output: " + + expectedResult.size() + + ", Size of output received: " + + resultReceived.size() + + "\n\tExpected Output: " + + expectedResult.get(index) + + ",\n\tOutput Received: none\n"; + + } + } + } + + } + if(index==expectedResult.size() && index==resultReceived.size() && returnString.equals("")){ + returnString="PASSED"; + } + return returnString; + + } +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GetConfigSample.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GetConfigSample.java new file mode 100644 index 000000000..cdba1c9fe --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GetConfigSample.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.util.Collection; + +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.PolicyConfig; +import org.openecomp.policy.api.PolicyEngine; + +public class GetConfigSample { + + public static void main(String[] args) throws Exception { + PolicyEngine pe = new PolicyEngine("config.properties"); + ConfigRequestParameters configRequestParams = new ConfigRequestParameters(); + configRequestParams.setPolicyName(".*"); + Collection configs = pe.getConfig(configRequestParams); + for (PolicyConfig config: configs){ + System.out.println(config.getPolicyConfigMessage()); + System.out.println(config.getPolicyConfigStatus()); + } + } +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/Handler.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/Handler.java new file mode 100644 index 000000000..448b54270 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/Handler.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.util.Collection; + +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.NotificationHandler; +import org.openecomp.policy.api.NotificationType; +import org.openecomp.policy.api.PDPNotification; +import org.openecomp.policy.api.PolicyConfig; +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyEngineException; +import org.openecomp.policy.api.RemovedPolicy; + +public class Handler implements NotificationHandler{ + + @Override + public void notificationReceived(PDPNotification notification) { + System.out.println("Notification Received..."); + System.out.println(notification.getNotificationType()); + if(notification.getNotificationType().equals(NotificationType.REMOVE)){ + System.out.println("Removed Policies: \n"); + for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ + System.out.println(removedPolicy.getPolicyName()); + System.out.println(removedPolicy.getVersionNo()); + } + }else if(notification.getNotificationType().equals(NotificationType.UPDATE)){ + System.out.println("Updated Policies: \n"); + for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ + System.out.println("policyName : " + updatedPolicy.getPolicyName()); + System.out.println("policyVersion :" + updatedPolicy.getVersionNo()); + if(updatedPolicy.getPolicyName().contains(".Config_")){ + System.out.println("Matches: " + updatedPolicy.getMatches()); + System.out.println("UpdateType: "+ updatedPolicy.getUpdateType()); + // Checking the Name is correct or not. + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + Collection policyConfigs = policyEngine.getConfigByPolicyName(updatedPolicy.getPolicyName()); + for(PolicyConfig policyConfig: policyConfigs){ + if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ + System.out.println("Policy Retrieved with this Name notified. "); + }else{ + System.err.println("\n\n Fail to retrieve policy !!!!\n\n"); + } + // Also Test this case. + if(policyConfig.getPolicyName().equals(updatedPolicy.getPolicyName())){ + System.out.println("Policy Name is good. "); + }else{ + System.err.println("\n\n Fail to check Name \n\n"); + } + } + } catch (PolicyEngineException e) { + e.printStackTrace(); + } catch (PolicyConfigException e) { + e.printStackTrace(); + } + } + } + }else if(notification.getNotificationType().equals(NotificationType.BOTH)){ + System.out.println("Both updated and Removed Notification: \n"); + System.out.println("Removed Policies: \n"); + for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ + System.out.println(removedPolicy.getPolicyName()); + System.out.println(removedPolicy.getVersionNo()); + } + System.out.println("Updated Policies: \n"); + for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ + System.out.println("policyName : " + updatedPolicy.getPolicyName()); + System.out.println("policyVersion :" + updatedPolicy.getVersionNo()); + System.out.println("Matches: " + updatedPolicy.getMatches()); + System.out.println("UpdateType: "+ updatedPolicy.getUpdateType()); + // Checking the Name is correct or not. + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + Collection policyConfigs = policyEngine.getConfigByPolicyName(updatedPolicy.getPolicyName()); + for(PolicyConfig policyConfig: policyConfigs){ + if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ + System.out.println("Policy Retrieved with this Name notified. "); + }else{ + System.err.println("\n\n Fail to retrieve policy !!!!\n\n"); + } + // Also Test this case. + if(policyConfig.getPolicyName().equals(updatedPolicy.getPolicyName())){ + System.out.println("Policy Name is good. "); + }else{ + System.err.println("\n\n Fail to check Name \n\n"); + } + } + } catch (PolicyEngineException e) { + e.printStackTrace(); + } catch (PolicyConfigException e) { + e.printStackTrace(); + } + } + } + } + + + +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ImportMicroServiceClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ImportMicroServiceClient.java new file mode 100644 index 000000000..ffb49d5ed --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ImportMicroServiceClient.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.openecomp.policy.api.ImportParameters; +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.ImportParameters.IMPORT_TYPE; + +public class ImportMicroServiceClient { + static Boolean isEdit = false; + public static void main(String[] args) { + try{ + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + ImportParameters importParameters = new ImportParameters(); + List filepath = new ArrayList(); + importParameters.setFilePath("C:\\Workspaces\\models\\TestingModel\\ControllerServiceSampleSdnlServiceInstance-v0.1.0-SNAPSHOT.zip"); + importParameters.setServiceName("ControllerServiceSampleSdnlServiceInstance"); + + importParameters.setRequestID(UUID.randomUUID()); + importParameters.setServiceType(IMPORT_TYPE.MICROSERVICE); + importParameters.setVersion("1607-2"); + + // API method to create Policy or update policy + PolicyChangeResponse response = null; + response = policyEngine.policyEngineImport(importParameters); + System.out.println(response.getResponseMessage()); + + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } + +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ListConfigPoliciesClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ListConfigPoliciesClient.java new file mode 100644 index 000000000..fa013bb69 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ListConfigPoliciesClient.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyEngineException; +import org.w3c.dom.Document; + +public class ListConfigPoliciesClient { + public static void main(String[] args) { + PolicyEngine policyEngine; + + // List Config Policies Example + try { + policyEngine = new PolicyEngine("config.properties"); + ConfigRequestParameters parameters = new ConfigRequestParameters(); + + parameters.setPolicyName(".*"); + parameters.setEcompName(".*"); + parameters.setConfigName(".*"); + + Map configAttributes = new HashMap(); + configAttributes.put("java", "java"); + configAttributes.put("peach", "Tar"); + configAttributes.put("true", "false"); + configAttributes.put("small", "testPass"); + parameters.setConfigAttributes(configAttributes); + + parameters.setRequestID(UUID.randomUUID()); + + Collection response = policyEngine.listConfig(parameters); + if(response!=null && !response.contains("PE300")){ + for(String configList : response){ + System.out.println(configList.toString()+"\n"); + } + }else{ + System.out.println("Error! " +response); + } + + } catch (PolicyConfigException e) { + e.printStackTrace(); + } catch (PolicyEngineException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MainClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MainClient.java new file mode 100644 index 000000000..e7a2f8195 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MainClient.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.NotificationScheme; +import org.openecomp.policy.api.PolicyConfig; +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyEngineException; +import org.openecomp.policy.api.PolicyType; +import org.openecomp.policy.api.RemovedPolicy; +import org.w3c.dom.Document; + +public class MainClient { + public static void main(String[] args) { + PolicyEngine policyEngine; + try { + policyEngine = new PolicyEngine("config.properties"); + String eCOMPComponentName = ".*" ; + String configName = ".*" ; + Map configAttributes = new HashMap(); + configAttributes.put("java", "java"); + configAttributes.put("peach", "Tar"); + configAttributes.put("true", "false"); + configAttributes.put("small", "testPass"); + Map eventAttributes = new HashMap(); + eventAttributes.put("true", "true"); + eventAttributes.put("cpu", "91"); + Map decisionAttributes = new HashMap(); + decisionAttributes.put("Key", "Value"); + + // Config Example + try { + Collection policyConfigs = policyEngine.getConfigByPolicyName(".*");//(eCOMPComponentName, configName, configAttributes); + if(policyConfigs!=null && !policyConfigs.isEmpty()){ + for(PolicyConfig policyConfig: policyConfigs){ + System.out.println("\nConfig Message: "+ policyConfig.getPolicyConfigMessage()); + System.out.println("Config Status: " + policyConfig.getPolicyConfigStatus()); + System.out.println("Policy Name: "+ policyConfig.getPolicyName()); + System.out.println("policy Version: " + policyConfig.getPolicyVersion()); + /*System.out.println("policy Type: " + policyConfig.getType().toString()); + System.out.println("Matching Conditions: " + policyConfig.getMatchingConditions()); + System.out.println("Body is : "); + if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ + if(policyConfig.getType().equals(PolicyType.OTHER)){ + System.out.println(policyConfig.toOther()); + }else if(policyConfig.getType().equals(PolicyType.JSON)){ + System.out.println(policyConfig.toJSON().toString()); + }else if(policyConfig.getType().equals(PolicyType.PROPERTIES)){ + System.out.println(policyConfig.toProperties().toString()); + }else if(policyConfig.getType().equals(PolicyType.XML)){ + try { + printDocument(policyConfig.toXML(), System.out); + } catch (Exception e) { + e.printStackTrace(); + } + } + }*/ + } + } + } catch (PolicyConfigException e) { + e.printStackTrace(); + } + // Action example + /*try{ + Collection policyResponses = org.openecomp.policyEngine.sendEvent(eventAttributes); + if(policyResponses!=null && !policyResponses.isEmpty()){ + for(PolicyResponse policyResponse: policyResponses){ + System.out.println(policyResponse.getPolicyResponseMessage() + " : " + policyResponse.getPolicyResponseStatus()); + System.out.println(policyResponse.getActionAdvised()); + System.out.println(policyResponse.getActionTaken()); + System.out.println(policyResponse.getRequestAttributes()); + } + } + }catch (PolicyEventException e){ + e.printStackTrace(); + }*/ + /*// Decision example + try{ + PolicyDecision policyDecision = org.openecomp.policyEngine.getDecision(eCOMPComponentName, decisionAttributes); + System.out.println(policyDecision.toString()); + } catch(PolicyDecisionException e){ + e.printStackTrace(); + }*/ + + // Manual Notifications.. + policyEngine.setScheme(NotificationScheme.MANUAL_ALL_NOTIFICATIONS); + if(policyEngine.getNotification()!=null){ + System.out.println(policyEngine.getNotification().getNotificationType()); + for(LoadedPolicy updated: policyEngine.getNotification().getLoadedPolicies()){ + System.out.println(updated.getPolicyName()); + System.out.println(updated.getVersionNo()); + System.out.println(updated.getMatches()); + } + for(RemovedPolicy removed: policyEngine.getNotification().getRemovedPolicies()){ + System.out.println(removed.getPolicyName()); + System.out.println(removed.getVersionNo()); + } + } + // Auto Notifications.. + Handler handler = new Handler(); + policyEngine.setNotification(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler); + // + System.out.println("Enter a any key to exit"); + try { + System.in.read(); + } catch (IOException e) { + // + } + + } catch (PolicyEngineException e1) { + e1.printStackTrace(); + } + } + + public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException { + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); + + transformer.transform(new DOMSource(doc), + new StreamResult(new OutputStreamWriter(out, "UTF-8"))); + } +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java new file mode 100644 index 000000000..4021c9432 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; +public class MicroServicesPolicyClient { + +//For updating a Micro Services policy set the "isEdit" flag to true. +//For creating a Micro Services policy set the "isEdit" flag to false. +static Boolean isEdit = false; + +//Builds JSONObject from File +private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException { + JsonObject json = null;; + + if (jsonString != null && jsonInput == null) { + StringReader in = null; + in = new StringReader(jsonString); + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + else { + InputStream in = null; + in = new FileInputStream(jsonInput); + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + + return json; +} +public static void main(String[] args) { + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + // Set Policy Type + policyParameters.setPolicyConfigType(PolicyConfigType.MicroService); + policyParameters.setPolicyName("Katrina.configuration_dcae_microservice_stringmatcher"); + //policyParameters.setPolicyDescription("This is a sample Micro Service policy Create example"); + policyParameters.setEcompName("DCAE"); + //policyParameters.setConfigName("Collector"); + //policyParameters.setPriority("1"); + //policyParameters.setPolicyScope("service=vSCP;resource=F5;type=configuration;closedLoopControlName=vSCP_F5_Firewall_d925ed73-8231-4d02-9545-db4e113213abab322"); + + // Set up Micro Services Attributes + File jsonFile = null; + String MSjsonString= null; + if (MSjsonString == null) { + Path file = Paths.get("C:\\policyAPI\\MicroServicesJSON\\testStringMatching.json"); + jsonFile = file.toFile(); + } + policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString()); + policyParameters.setConfigBodyType(PolicyType.JSON); + + policyParameters.setRequestID(UUID.randomUUID()); + // Set Safe Policy value for Risk Type + SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy"); + Date date = dateformat3.parse("15/10/2016"); + policyParameters.setTtlDate(date); + // Set Safe Policy value for Guard + policyParameters.setGuard(true); + // Set Safe Policy value for Risk Level + policyParameters.setRiskLevel("5"); + // Set Safe Policy value for Risk Type + policyParameters.setRiskType("PROD"); + + // API method to create or update Policy. + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } + else { + response = policyEngine.updatePolicy(policyParameters); + } + + if(response.getResponseCode()==200){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PolicyEngineTestClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PolicyEngineTestClient.java new file mode 100644 index 000000000..f2606a971 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PolicyEngineTestClient.java @@ -0,0 +1,201 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * 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========================================================= + */ + +/* + * AT&T - PROPRIETARY + * THIS FILE CONTAINS PROPRIETARY INFORMATION OF + * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN + * ACCORDANCE WITH APPLICABLE AGREEMENTS. + * + * Copyright (c) 2014 AT&T Knowledge Ventures + * Unpublished and Not for Publication + * All Rights Reserved + */ +package org.openecomp.policyEngine; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.UUID; + +import org.openecomp.policy.api.DecisionResponse; +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.NotificationScheme; +import org.openecomp.policy.api.PolicyConfig; +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.api.PolicyDecisionException; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PolicyEventException; +import org.openecomp.policy.api.PolicyResponse; +import org.openecomp.policy.api.RemovedPolicy; + +/** + * Class contains static functions which make call to policy engine using API. + * This class is used by generalTestClient.java + * + * + * @version 1.0 + * + */ +public class PolicyEngineTestClient { + /** + * This fuction make API call to policy engine to get config. And returns + * policy name, policy version and policy configStatus + * + * @param org.openecomp.policyEngine + * @param eCOMPComponentName + * @param configName + * @param configAttributes + * @return + */ + + public static ArrayList getConfig(PolicyEngine policyEngine, + String eCOMPComponentName, String configName, + Map configAttributes) { + ArrayList resultReceived = new ArrayList(); + try { + UUID requestID = UUID.randomUUID(); + Collection policyConfigs; + if (configName == null) { + policyConfigs = policyEngine.getConfig(eCOMPComponentName, requestID); + } else { + if (configAttributes == null) { + policyConfigs = policyEngine.getConfig(eCOMPComponentName, + configName, requestID); + } else { + + policyConfigs = policyEngine.getConfig(eCOMPComponentName, + configName, configAttributes, requestID); + } + } + if (policyConfigs != null && !policyConfigs.isEmpty()) { + for (PolicyConfig policyConfig : policyConfigs) { + resultReceived.add("Policy Name: " + + policyConfig.getPolicyName() + + " Policy version: " + + policyConfig.getPolicyVersion() + " - " + + policyConfig.getPolicyConfigStatus()); + } + } + } catch (PolicyConfigException e) { +// e.printStackTrace(); + resultReceived.add(""+e); + } + return resultReceived; + } + + /** + * This functions make API call to policy engine to get decision. And + * returns policy Decision + * + * @param org.openecomp.policyEngine + * @param eCOMPComponentName + * @param decisionAttributes + * @return + */ + public static ArrayList getDecision(PolicyEngine policyEngine, + String eCOMPComponentName, Map decisionAttributes) { + ArrayList resultReceived = new ArrayList(); + // Decision example + try { + UUID requestID = UUID.randomUUID(); + DecisionResponse policyDecision = policyEngine.getDecision( + eCOMPComponentName, decisionAttributes, requestID); + resultReceived.add(policyDecision.getDecision().toString()); + } catch (PolicyDecisionException e) { +// e.printStackTrace(); + resultReceived.add(""+e); + } + return resultReceived; + } + + /** + * This function makes API call to policy engine to get action. And returns + * responseMessage and responseStatus + * + * @param org.openecomp.policyEngine + * @param eventAttributes + * @return + */ + public static ArrayList getAction(PolicyEngine policyEngine, + Map eventAttributes) { + ArrayList resultReceived = new ArrayList(); + try { + UUID requestID = UUID.randomUUID(); + Collection policyResponses = policyEngine + .sendEvent(eventAttributes, requestID); + if (policyResponses != null && !policyResponses.isEmpty()) { + for (PolicyResponse policyResponse : policyResponses) { + resultReceived.add(policyResponse + .getPolicyResponseMessage() + + " : " + + policyResponse.getPolicyResponseStatus()); + } + } + } catch (PolicyEventException e) { +// e.printStackTrace(); + resultReceived.add(""+e); + } + return resultReceived; + } + + /** + * This function makes API call to policy engine to get manual + * notifications. + * + * @param org.openecomp.policyEngine + */ + + public static void getManualNotifications(PolicyEngine policyEngine) { + policyEngine.setScheme(NotificationScheme.MANUAL_ALL_NOTIFICATIONS); + System.out.println(policyEngine.getNotification().getNotificationType()); + for (LoadedPolicy updated : policyEngine.getNotification().getLoadedPolicies()) { + System.out.println(updated.getPolicyName()); + System.out.println(updated.getVersionNo()); + System.out.println(updated.getMatches()); + } + for (RemovedPolicy removed : policyEngine.getNotification() + .getRemovedPolicies()) { + System.out.println(removed.getPolicyName()); + System.out.println(removed.getVersionNo()); + } + } + + /** + * This function makes API call to policy engine to get automatic + * notifications. + * + * @param org.openecomp.policyEngine + */ + public static void getAutoNotifications(PolicyEngine policyEngine) { + Handler handler = new Handler(); + policyEngine.setNotification(NotificationScheme.AUTO_ALL_NOTIFICATIONS, + handler); + // + System.out.println("Enter a any key to exit"); + try { + System.in.read(); + } catch (IOException e) { + // + } + } + +} diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PushPoliciesToPDP.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PushPoliciesToPDP.java new file mode 100644 index 000000000..2a4086357 --- /dev/null +++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PushPoliciesToPDP.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policyEngine; + +import org.openecomp.policy.api.PolicyChangeResponse; +import org.openecomp.policy.api.PolicyEngine; +import org.openecomp.policy.api.PushPolicyParameters; + +public class PushPoliciesToPDP { + public static void main(String[] args) { + try { + + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PushPolicyParameters policyParameters = new PushPolicyParameters(); + + //Parameter arguments + policyParameters.setPolicyName("Mike.testCase1"); + policyParameters.setPolicyType("Base"); + //policyParameters.setPolicyScope("MikeAPItesting"); + policyParameters.setPdpGroup("default"); + policyParameters.setRequestID(null); + + // API method to Push Policy to PDP + PolicyChangeResponse response = null; + response = policyEngine.pushPolicy(policyParameters); + + if(response.getResponseCode()==204){ + System.out.println(response.getResponseMessage()); + System.out.println("Policy Pushed Successfully!"); + }else{ + System.out.println("Error! " + response.getResponseMessage()); + } + + } catch (Exception e) { + System.err.println(e.getMessage()); + + } + + } + +} -- cgit 1.2.3-korg