diff options
author | Jorge Hernandez <jh1730@att.com> | 2017-08-23 19:35:20 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2017-08-23 19:35:20 +0000 |
commit | 7ea81288603904f0cb6f57936da44d6a3dd521a6 (patch) | |
tree | 192c5dc897ced8996e864644b4d6f46e4d55081a /PolicyEngineClient/src/test/java/org/onap | |
parent | 3144162991b83e3c4f3d1a240a65d8497042c718 (diff) | |
parent | 80f072f60509ef3a35369a60857fe05f6c2a993a (diff) |
Merge "Fixes for sonar critical issues"
Diffstat (limited to 'PolicyEngineClient/src/test/java/org/onap')
19 files changed, 2219 insertions, 0 deletions
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java new file mode 100644 index 000000000..94c6043c5 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java @@ -0,0 +1,111 @@ +/*- + * ============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.onap.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.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyParameters; + +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<String, String> configAttributes = new HashMap<>(); + configAttributes.put("Template", "UpdateTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + + Map<AttributeType, Map<String,String>> attributes = new HashMap<>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + + + List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); + List<String> dynamicRuleAlgorithmFunctions = new LinkedList<>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); + List<String> 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() + e); + } + } + +} + + diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java new file mode 100644 index 000000000..33ceedf7f --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java @@ -0,0 +1,96 @@ +/*- + * ============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.onap.policyengine; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.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 BRMS Param Template Attributes(Mandatory) + Map<String, String> 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<AttributeType, Map<String, String>> 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() + e); + } + + } + +} + + diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java new file mode 100644 index 000000000..18d404dc2 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java @@ -0,0 +1,131 @@ +/*- + * ============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.onap.policyengine; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyParameters; +import org.onap.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<String, String> attrib= new HashMap<>(); + attrib.put("cpu","80"); + attrib.put("memory", "50"); + Map<AttributeType, Map<String, String>> 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<String,String> 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/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java new file mode 100644 index 000000000..29a0f4363 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java @@ -0,0 +1,125 @@ +/*- + * ============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.onap.policyengine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +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.Date; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyParameters; +import org.onap.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;; + JsonReader jsonReader = null; + if (jsonString != null && jsonInput == null) { + StringReader in = null; + in = new StringReader(jsonString); + jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + in.close(); + }else { + InputStream in = null; + in = new FileInputStream(jsonInput); + jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + try { + in.close(); + } catch (IOException e) { + System.err.println("Exception Occured while closing input stream"+e); + } + } + jsonReader.close(); + + 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; + 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/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java new file mode 100644 index 000000000..eaee2a325 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java @@ -0,0 +1,127 @@ +/*- + * ============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.onap.policyengine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +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.Date; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyParameters; +import org.onap.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;; + JsonReader jsonReader = null; + if (jsonString != null && jsonInput == null) { + StringReader in = null; + in = new StringReader(jsonString); + jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + in.close(); + } + else { + InputStream in = null; + in = new FileInputStream(jsonInput); + jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + try { + in.close(); + } catch (IOException e) { + System.err.println("Exception Occured while closing input stream"+e); + } + } + jsonReader.close(); + 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; + 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/test/java/org/onap/policyengine/ConfigBasePolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigBasePolicyClient.java new file mode 100644 index 000000000..b8dfdc1f6 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/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.onap.policyengine; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyParameters; +import org.onap.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.setOnapName("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<String, String> configAttributes = new HashMap<>(); + configAttributes.put("Template", "SampleTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + Map<AttributeType, Map<String,String>> 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/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java new file mode 100644 index 000000000..37ec9fabd --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.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.onap.policyengine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +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.Date; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyParameters; +import org.onap.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; + 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; + JsonReader jsonReader = null; + if (jsonString != null && jsonInput == null) { + StringReader in = null; + in = new StringReader(jsonString); + jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + in.close(); + } else { + InputStream in = null; + in = new FileInputStream(jsonInput); + jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + try { + in.close(); + } catch (IOException e) { + System.err.println("Exception Occured while closing input stream"+e); + } + } + jsonReader.close(); + return json; + } + +} diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java new file mode 100644 index 000000000..2ef2d3b1a --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java @@ -0,0 +1,114 @@ +/*- + * ============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.onap.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.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyEngine; +import org.onap.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.setOnapName("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<String, String> configAttributes = new HashMap<>(); + configAttributes.put("Template", "UpdateTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + + Map<AttributeType, Map<String,String>> attributes = new HashMap<>(); + attributes.put(AttributeType.MATCHING, configAttributes); + + //Set the settings... These are Optional + Map<String, String> settingsMap = new HashMap<>(); + settingsMap.put("server", "5"); + + attributes.put(AttributeType.SETTINGS, settingsMap); + policyParameters.setAttributes(attributes); + + + List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); + List<String> dynamicRuleAlgorithmFunctions = new LinkedList<>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); + List<String> 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/test/java/org/onap/policyengine/DeletePolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/DeletePolicyClient.java new file mode 100644 index 000000000..c66067942 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/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.onap.policyengine; + +import org.onap.policy.api.DeletePolicyCondition; +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.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/test/java/org/onap/policyengine/GeneralTestClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java new file mode 100644 index 000000000..e81939be6 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java @@ -0,0 +1,400 @@ +/*- + * ============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.onap.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.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +/** + * 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 { + + private static final Logger LOGGER = FlexLogger.getLogger(GeneralTestClient.class); + + 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, onapComponentName; + 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<String> expectedResult = new ArrayList<>(); + ArrayList<String> 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": + onapComponentName = (String) testCase + .get("ONAPName"); + String configName = (String) testCase + .get("ConfigName"); + Map<String, String> 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, onapComponentName, + 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<String, String> 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": + onapComponentName = (String) testCase + .get("ONAPName"); + Map<String, String> 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, + onapComponentName, + 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.onap.policyEngine); + // break; + // case "getAutoNotification": + // PolicyEngineTestClient + // .getAutoNotifications(org.onap.policyEngine); + // break; + + default: + printResult(id, testFor, testCaseDescription, + "FAILED", "\tINVAILD TEST CASE."); + failTCforFile++; + failTC++; + break; + + } + } catch (PolicyEngineException e) { + printResult(id, testFor, testCaseDescription, "FAILED"); + failTCforFile++; + failTC++; + LOGGER.error("Exception Occured"+e); + } catch (Exception e) { + printResult(id, testFor, testCaseDescription, "FAILED"); + failTCforFile++; + failTC++; + LOGGER.error("Exception Occured"+e); + } + } + + } catch (FileNotFoundException ex) { + LOGGER.error("Exception Occured due to File not found"+ex); + } catch (IOException ex) { + LOGGER.error("Exception Occured"+ex); + } catch (NullPointerException ex) { + LOGGER.error("Exception Occured due to Null Pointer"+ex); + } catch (org.json.simple.parser.ParseException e) { + LOGGER.error("Exception Occured while Parsing"+e); + } + } + 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<String> expectedResult, + ArrayList<String> 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/test/java/org/onap/policyengine/GetConfigSample.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/GetConfigSample.java new file mode 100644 index 000000000..94cc69fd7 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/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.onap.policyengine; + +import java.util.Collection; + +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.PolicyConfig; +import org.onap.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<PolicyConfig> configs = pe.getConfig(configRequestParams); + for (PolicyConfig config: configs){ + System.out.println(config.getPolicyConfigMessage()); + System.out.println(config.getPolicyConfigStatus()); + } + } +} diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java new file mode 100644 index 000000000..12fca6e93 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java @@ -0,0 +1,127 @@ +/*- + * ============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.onap.policyengine; + +import java.util.Collection; + +import org.onap.policy.api.LoadedPolicy; +import org.onap.policy.api.NotificationHandler; +import org.onap.policy.api.NotificationType; +import org.onap.policy.api.PDPNotification; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.RemovedPolicy; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class Handler implements NotificationHandler{ + + private static final Logger LOGGER = FlexLogger.getLogger(Handler.class); + + @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"); + @SuppressWarnings("deprecation") + Collection<PolicyConfig> 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) { + LOGGER.error("Exception Occured"+e); + } catch (PolicyConfigException e) { + LOGGER.error("Exception Occured"+e); + } + } + } + }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"); + @SuppressWarnings("deprecation") + Collection<PolicyConfig> 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) { + LOGGER.error("Exception Occured"+e); + } catch (PolicyConfigException e) { + LOGGER.error("Exception Occured"+e); + } + } + } + } + + + +} diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java new file mode 100644 index 000000000..ef9ec3136 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java @@ -0,0 +1,30 @@ +package org.onap.policyengine; + +import java.io.File; +import java.util.UUID; + +import org.onap.policy.api.ImportParameters; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.ImportParameters.IMPORT_TYPE; + +public class ImportBRMSTemplate { + public static void main(String[] args) { + try{ + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + ImportParameters importParameters = new ImportParameters(); + importParameters.setFilePath("testResources"+File.separator+"test.drl"); + importParameters.setServiceName("testTemplate"); + importParameters.setRequestID(UUID.randomUUID()); + importParameters.setServiceType(IMPORT_TYPE.BRMSPARAM); + + // 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/test/java/org/onap/policyengine/ImportMicroServiceClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java new file mode 100644 index 000000000..86439583a --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java @@ -0,0 +1,53 @@ +/*- + * ============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.onap.policyengine; + +import java.util.UUID; + +import org.onap.policy.api.ImportParameters; +import org.onap.policy.api.ImportParameters.IMPORT_TYPE; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyEngine; + +public class ImportMicroServiceClient { + static Boolean isEdit = false; + public static void main(String[] args) { + try{ + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + ImportParameters importParameters = new ImportParameters(); + 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/test/java/org/onap/policyengine/ListConfigPoliciesClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java new file mode 100644 index 000000000..9973ce70c --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java @@ -0,0 +1,76 @@ +/*- + * ============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.onap.policyengine; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class ListConfigPoliciesClient { + + private static final Logger LOGGER = FlexLogger.getLogger(ListConfigPoliciesClient.class); + + 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.setOnapName(".*"); + parameters.setConfigName(".*"); + + Map<String, String> 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<String> 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) { + LOGGER.error("Exception Occured"+e); + } catch (PolicyEngineException e) { + LOGGER.error("Exception Occured"+e); + } + } + +} diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java new file mode 100644 index 000000000..210499ca1 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java @@ -0,0 +1,125 @@ +/*- + * ============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.onap.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.onap.policy.api.LoadedPolicy; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.RemovedPolicy; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.w3c.dom.Document; + +public class MainClient { + + private static final Logger LOGGER = FlexLogger.getLogger(MainClient.class); + + public static void main(String[] args) { + PolicyEngine policyEngine; + try { + policyEngine = new PolicyEngine("config.properties"); + Map<String, String> configAttributes = new HashMap<>(); + configAttributes.put("java", "java"); + configAttributes.put("peach", "Tar"); + configAttributes.put("true", "false"); + configAttributes.put("small", "testPass"); + Map<String, String> eventAttributes = new HashMap<>(); + eventAttributes.put("true", "true"); + eventAttributes.put("cpu", "91"); + Map<String, String> decisionAttributes = new HashMap<>(); + decisionAttributes.put("Key", "Value"); + + // Config Example + try { + @SuppressWarnings("deprecation") + Collection<PolicyConfig> policyConfigs = policyEngine.getConfigByPolicyName(".*");//(onapComponentName, 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()); + } + } + } catch (PolicyConfigException e) { + LOGGER.error("Exception Occured"+e); + } + + // 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) { + System.err.println("Exception Occured"+e); + } + + } catch (PolicyEngineException e1) { + System.err.println("Exception Occured"+e1); + } + } + + 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/test/java/org/onap/policyengine/MicroServicesPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java new file mode 100644 index 000000000..b05e44726 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java @@ -0,0 +1,127 @@ +/*- + * ============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.onap.policyengine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +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.Date; +import java.util.UUID; +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyParameters; +import org.onap.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;; + JsonReader jsonReader = null; + if (jsonString != null && jsonInput == null) { + StringReader in = null; + in = new StringReader(jsonString); + jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + in.close(); + } + else { + InputStream in = null; + in = new FileInputStream(jsonInput); + jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + try { + in.close(); + } catch (IOException e) { + System.err.println("Exception Occured while closing input stream"+e); + } + } + jsonReader.close(); + 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.setOnapName("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; + 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/test/java/org/onap/policyengine/PolicyEngineTestClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java new file mode 100644 index 000000000..39346eaea --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java @@ -0,0 +1,204 @@ +/*- + * ============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.onap.policyengine; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.api.DecisionResponse; +import org.onap.policy.api.LoadedPolicy; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyDecisionException; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEventException; +import org.onap.policy.api.PolicyResponse; +import org.onap.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.onap.policyEngine + * @param onapComponentName + * @param configName + * @param configAttributes + * @return + */ + + @SuppressWarnings("deprecation") + public static ArrayList<String> getConfig(PolicyEngine policyEngine, + String onapComponentName, String configName, + Map<String, String> configAttributes) { + ArrayList<String> resultReceived = new ArrayList<>(); + try { + UUID requestID = UUID.randomUUID(); + Collection<PolicyConfig> policyConfigs; + if (configName == null) { + policyConfigs = policyEngine.getConfig(onapComponentName, requestID); + } else { + if (configAttributes == null) { + policyConfigs = policyEngine.getConfig(onapComponentName, + configName, requestID); + } else { + + policyConfigs = policyEngine.getConfig(onapComponentName, + 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) { +// logger.error("Exception Occured"+e); + resultReceived.add(""+e); + } + return resultReceived; + } + + /** + * This functions make API call to policy engine to get decision. And + * returns policy Decision + * + * @param org.onap.policyEngine + * @param onapComponentName + * @param decisionAttributes + * @return + */ + public static ArrayList<String> getDecision(PolicyEngine policyEngine, + String onapComponentName, Map<String, String> decisionAttributes) { + ArrayList<String> resultReceived = new ArrayList<>(); + // Decision example + try { + UUID requestID = UUID.randomUUID(); + @SuppressWarnings("deprecation") + DecisionResponse policyDecision = policyEngine.getDecision( + onapComponentName, decisionAttributes, requestID); + resultReceived.add(policyDecision.getDecision().toString()); + } catch (PolicyDecisionException e) { +// logger.error("Exception Occured"+e); + resultReceived.add(""+e); + } + return resultReceived; + } + + /** + * This function makes API call to policy engine to get action. And returns + * responseMessage and responseStatus + * + * @param org.onap.policyEngine + * @param eventAttributes + * @return + */ + public static ArrayList<String> getAction(PolicyEngine policyEngine, + Map<String, String> eventAttributes) { + ArrayList<String> resultReceived = new ArrayList<>(); + try { + UUID requestID = UUID.randomUUID(); + @SuppressWarnings("deprecation") + Collection<PolicyResponse> policyResponses = policyEngine + .sendEvent(eventAttributes, requestID); + if (policyResponses != null && !policyResponses.isEmpty()) { + for (PolicyResponse policyResponse : policyResponses) { + resultReceived.add(policyResponse + .getPolicyResponseMessage() + + " : " + + policyResponse.getPolicyResponseStatus()); + } + } + } catch (PolicyEventException e) { +// logger.error("Exception Occured"+e); + resultReceived.add(""+e); + } + return resultReceived; + } + + /** + * This function makes API call to policy engine to get manual + * notifications. + * + * @param org.onap.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.onap.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/test/java/org/onap/policyengine/PushPoliciesToPDP.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/PushPoliciesToPDP.java new file mode 100644 index 000000000..880af0610 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/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.onap.policyengine; + +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyEngine; +import org.onap.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()); + + } + + } + +} |