diff options
Diffstat (limited to 'PolicyEngineClient')
24 files changed, 2840 insertions, 0 deletions
diff --git a/PolicyEngineClient/.gitignore b/PolicyEngineClient/.gitignore new file mode 100644 index 000000000..b83d22266 --- /dev/null +++ b/PolicyEngineClient/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/PolicyEngineClient/config.properties b/PolicyEngineClient/config.properties new file mode 100644 index 000000000..4bc176d53 --- /dev/null +++ b/PolicyEngineClient/config.properties @@ -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========================================================= +### + +# PIP Engine Definition +PDP_URL1 = http://localhost:8081/pdp/ , testpdp , alpha123 +PAP_URL = http://localhost:9091/pap/ , testpap , alpha123 +#PDP_URL1 = http://localhost:8082/pdp/, testpdp, alpha456 +#PAP_URL = http://localhost:8070/pap/, testpap, alpha123 +NOTIFICATION_TYPE=websocket +NOTIFICATION_UEB_SERVERS=localhost.com +CLIENT_ID= +CLIENT_KEY=PolicyR0ck$ +ENVIRONMENT=TEST + +########################################### +## FOR CONNECTION TO THE IST PAP AND PDP ## +########################################### +#PAP_URL=http://localhost:9091/pap/ , testpap, alpha123 +#PAP_URL=http://localhost:9091/pap/,testpap,alpha123 +#PDP_URL1=http://localhost:8081/pdp/ , testpdp, alpha123 +#PDP_URL2=http://localhost:8081/pdp/ , testpdp, alpha123 +#NOTIFICATION_TYPE=ueb +#NOTIFICATION_UEB_SERVERS=localhost.com +#CLIENT_ID=PyPDPServer +#CLIENT_KEY=test + + +########################################### +## FOR CONNECTION TO THE E2E PAP AND PDP ## +########################################### +#PDP_URL = http://localhost:8081/pdp/, testpdp, alpha123 +#PAP_URL = http://localhost:9091/pap/, testpap, alpha123 +#NOTIFICATION_TYPE=websocket +#NOTIFICATION_UEB_SERVERS=localhost.com +#CLIENT_ID=PyPDPServer +#CLIENT_KEY=test diff --git a/PolicyEngineClient/config.test.properties b/PolicyEngineClient/config.test.properties new file mode 100644 index 000000000..d9a955c2b --- /dev/null +++ b/PolicyEngineClient/config.test.properties @@ -0,0 +1,24 @@ +### +# ============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========================================================= +### + +PDP_URL= http://localhost:8082/pdp/, testpdp, alpha456 +PAP_URL = http://localhost:9090/pap/ , testpap, alpha123 +CLIENT_ID= +CLIENT_KEY= diff --git a/PolicyEngineClient/input.testCases b/PolicyEngineClient/input.testCases new file mode 100644 index 000000000..edb374001 --- /dev/null +++ b/PolicyEngineClient/input.testCases @@ -0,0 +1,419 @@ +[ +{ + "id": 1, + "testCaseDescription": "test GetConfig String Not valid", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "fail", + "ConfigName": null, + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 2, + "testCaseDescription": "test Get ConfigString Valid JSON", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "JSON", + "ConfigName": null, + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 3, + "testCaseDescription": "test Get ConfigString Valid XML", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "XML", + "ConfigName": null, + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 4, + "testCaseDescription": "test Get ConfigString Valid properties", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "Properties", + "ConfigName": null, + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 5, + "testCaseDescription": "test Get ConfigString Valid other", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "Other", + "ConfigName": null, + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 6, + "testCaseDescription": "test GetConfig String String Fail", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": null, + "ConfigName": null, + "configAttributes": null, + "expectedResult":[ + "org.openecomp.policy.api.PolicyConfigException: No eCOMPComponentName given.", + ] +}, +{ + "id": 7, + "testCaseDescription": "test GetConfig String String Fail1", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": null, + "ConfigName": null, + "configAttributes": null, + "expectedResult":[ + "org.openecomp.policy.api.PolicyConfigException: No eCOMPComponentName given." + + ] +}, +{ + "id": 8, + "testCaseDescription": "test GetConfig String String Valid ", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "fail", + "ConfigName": "fail", + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 9, + "testCaseDescription": "test GetConfig String String Valid JSON", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "JSON", + "ConfigName": "JSONconfig", + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 10, + "testCaseDescription": "test GetConfig String String Valid XML", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "XML", + "ConfigName": "XMLconfig", + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 11, + "testCaseDescription": "test GetConfig String String Valid properties", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "Properties", + "ConfigName": "PropConfig", + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 12, + "testCaseDescription": "test GetConfig String String Valid other", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "Other", + "ConfigName": "OtherConfig", + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 13, + "testCaseDescription": "test GetConfig String String String fail", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": null, + "ConfigName": null, + "configAttributes": null, + "expectedResult":[ + "org.openecomp.policy.api.PolicyConfigException: No eCOMPComponentName given." + ] +}, +{ + "id": 14, + "testCaseDescription": "test GetConfig String String String fail1", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": null, + "ConfigName": "testFail", + "configAttributes": [ + { + "key": "TestValue", + "value": "Fail", + }, + ], + "expectedResult":[ + "org.openecomp.policy.api.PolicyConfigException: No eCOMPComponentName given.", + ] +}, +{ + "id": 15, + "testCaseDescription": "test GetConfig String String String fail2", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "TestFail", + "ConfigName": null, + "configAttributes": [ + { + "key": "TestValue", + "value": "Fail", + }, + ], + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 16, + "testCaseDescription": "test GetConfig String String String fail3", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "TestFail", + "ConfigName": "configFail", + "configAttributes": null, + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 17, + "testCaseDescription": "test GetConfig String String String fail4", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "TestFail", + "ConfigName": "configFail", + "configAttributes": [ + { + "key": "", + "value": "", + }, + ], + "expectedResult":[ + "org.openecomp.policy.api.PolicyConfigException: Cannot have an empty Key", + + ] +}, +{ + "id": 18, + "testCaseDescription": "test GetConfig String String String Valid", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "TestFail", + "ConfigName": "configFail", + "configAttributes": [ + { + "key": "Action:com.test.fail", + "value": "Value", + }, + ], + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 19, + "testCaseDescription": "test GetConfig String String String Valid JSON", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "JSON", + "ConfigName": "JSONconfig", + "configAttributes": [ + { + "key": "Resource.com:test:resource:json", + "value":"Test", + }, + { + "key": "Action.com:test:action:json", + "value":"TestJSON", + }, + { + "key": "Subject.com:test:subject:json", + "value":"TestSubject", + } + ], + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 20, + "testCaseDescription": "test GetConfig String String String Valid XML", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "XML", + "ConfigName": "XMLconfig", + "configAttributes": [ + { + "key": "Resource.com:test:resource:json", + "value":"Test", + }, + { + "key": "Action.com:test:action:json", + "value":"TestJSON", + }, + { + "key": "Subject.com:test:subject:json", + "value":"TestSubject", + } + ], + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 21, + "testCaseDescription": "test GetConfig String String String Valid properties", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "Properties", + "ConfigName": "PropConfig", + "configAttributes": [ + { + "key": "Resource.com:test:resource:json", + "value":"Test", + }, + { + "key": "Action.com:test:action:json", + "value":"TestJSON", + }, + { + "key": "Subject.com:test:subject:json", + "value":"TestSubject", + } + ], + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 22, + "testCaseDescription": "test GetConfig String String String Valid other", + "testFor": "getConfig", + "PDP_URLConfigFile": "config.properties" + "ECOMPName": "Other", + "ConfigName": "OtherConfig", + "configAttributes": [ + { + "key": "Resource.com:test:resource:json", + "value":"Test", + }, + { + "key": "Action.com:test:action:json", + "value":"TestJSON", + }, + { + "key": "Subject.com:test:subject:json", + "value":"TestSubject", + } + ], + "expectedResult":[ + "Policy Name: null Policy version: null - not_found", + ] +}, +{ + "id": 23, + "testCaseDescription": "test SendEvent Fail", + "testFor": "getAction", + "PDP_URLConfigFile": "config.properties", + "eventAttributes": null, + "expectedResult":[ + "org.openecomp.policy.api.PolicyEventException: No EventAttributes Given.", + ] +}, +{ + "id": 24, + "testCaseDescription": "test SendEvent Fail null", + "testFor": "getAction", + "PDP_URLConfigFile": "config.properties", + "eventAttributes": [ + { + "key": "", + "value": "" + }, + ], + "expectedResult":[ + "org.openecomp.policy.api.PolicyEventException: Cannot have an empty Key", + + ] +}, +{ + "id": 25, + "testCaseDescription": "test SendEvent Not Valid", + "testFor": "getAction", + "PDP_URLConfigFile": "config.properties", + "eventAttributes": [ + { + "key": "Action.fail", + "value": "Value" + }, + ], + "expectedResult":[ + "Decision not a Permit. : no_action", + ] +}, +{ + "id": 26, + "testCaseDescription": "test SendEvent Action Advised", + "testFor": "getAction", + "PDP_URLConfigFile": "config.properties", + "eventAttributes": [ + { + "key": "Key", + "value": "Value" + }, + { + "key": "cpu", + "value": "80" + }, + ], + "expectedResult":[ + "Decision not a Permit. : no_action", + ] +}, +{ + "id": 27, + "testCaseDescription": "test SendEvent Action Taken", + "testFor": "getAction", + "PDP_URLConfigFile": "config.properties", + "eventAttributes": [ + { + "key": "Key", + "value": "Value" + }, + { + "key": "cpu", + "value": "91" + }, + ], + "expectedResult":[ + "Decision not a Permit. : no_action", + ] +}, +]
\ No newline at end of file diff --git a/PolicyEngineClient/policyLogger.properties b/PolicyEngineClient/policyLogger.properties new file mode 100644 index 000000000..3c3f3b5f5 --- /dev/null +++ b/PolicyEngineClient/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/PolicyEngineClient/pom.xml b/PolicyEngineClient/pom.xml new file mode 100644 index 000000000..8d667dd6c --- /dev/null +++ b/PolicyEngineClient/pom.xml @@ -0,0 +1,62 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + ECOMP Policy Engine + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.openecomp.policy.engine</groupId> + <artifactId>PolicyEngineSuite</artifactId> + <version>1.0.0-SNAPSHOT</version> + </parent> + <groupId>org.openecomp.policy.engine</groupId> + <artifactId>PolicyEngineClient</artifactId> + <dependencies> + <dependency> + <groupId>org.openecomp.policy.engine</groupId> + <artifactId>PolicyEngineAPI</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>com.googlecode.json-simple</groupId> + <artifactId>json-simple</artifactId> + <version>1.1</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5</version> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.2</version> + <configuration> + <source>1.8</source> + <target>1.8</target> + </configuration> + </plugin> + </plugins> + </build> +</project> 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<String, String> configAttributes = new HashMap<String, String>(); + configAttributes.put("Template", "UpdateTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + + Map<AttributeType, Map<String,String>> attributes = new HashMap<AttributeType, Map<String,String>>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + + //Set the Rule Algorithm + // Map<String, Map<String, Map<String, String>>> translated to Map<Dynamic Label, Map<Field1,Map<Combo Operator, Field2>>> + Map<String, Map<String,Map<String,String>>> ruleAlgorithm = new HashMap<String, Map<String,Map<String,String>>>(); + + List<String> dynamicRuleAlgorithmLabels = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmFunctions = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmField2 = new LinkedList<String>(); + + //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<String, String> ruleAttributes = new HashMap<String, String>(); + 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<AttributeType, Map<String, String>>(); + 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<String, String> attrib= new HashMap<String,String>(); + attrib.put("cpu","80"); + attrib.put("memory", "50"); + Map<AttributeType, Map<String, String>> attributes = new HashMap<AttributeType, Map<String, String>>(); + 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/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<String, String> configAttributes = new HashMap<String, String>(); + configAttributes.put("Template", "SampleTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + Map<AttributeType, Map<String,String>> attributes = new HashMap<AttributeType, Map<String,String>>(); + 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<String, String> configAttributes = new HashMap<String, String>(); + configAttributes.put("Template", "UpdateTemplate"); + configAttributes.put("controller", "default"); + configAttributes.put("SamPoll", "30"); + configAttributes.put("value", "abcd"); + + Map<AttributeType, Map<String,String>> attributes = new HashMap<AttributeType, Map<String,String>>(); + attributes.put(AttributeType.MATCHING, configAttributes); + + //Set the settings... These are Optional + Map<String, String> settingsMap = new HashMap<String, String>(); + settingsMap.put("server", "5"); + + attributes.put(AttributeType.SETTINGS, settingsMap); + policyParameters.setAttributes(attributes); + + //Set the Rule Algorithm... These are Optional + Map<String, Map<String,Map<String,String>>> ruleAlgorithm = new HashMap<String, Map<String,Map<String,String>>>(); + + List<String> dynamicRuleAlgorithmLabels = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmFunctions = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmField2 = new LinkedList<String>(); + + //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<String> expectedResult = new ArrayList<String>(); + ArrayList<String> resultReceived = new ArrayList<String>(); + 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<String, String> configAttributes = new HashMap<String, String>(); + 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<String, String> eventAttributes = new HashMap<String, String>(); + 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<String, String> decisionAttributes = new HashMap<String, String>(); + 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<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/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<PolicyConfig> 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<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) { + 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<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) { + 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<String> filepath = new ArrayList<String>(); + 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<String, String> configAttributes = new HashMap<String,String>(); + 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) { + 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<String, String> configAttributes = new HashMap<String,String>(); + configAttributes.put("java", "java"); + configAttributes.put("peach", "Tar"); + configAttributes.put("true", "false"); + configAttributes.put("small", "testPass"); + Map<String, String> eventAttributes = new HashMap<String,String>(); + eventAttributes.put("true", "true"); + eventAttributes.put("cpu", "91"); + Map<String, String> decisionAttributes = new HashMap<String,String>(); + decisionAttributes.put("Key", "Value"); + + // Config Example + try { + Collection<PolicyConfig> 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<PolicyResponse> 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<String> getConfig(PolicyEngine policyEngine, + String eCOMPComponentName, String configName, + Map<String, String> configAttributes) { + ArrayList<String> resultReceived = new ArrayList<String>(); + try { + UUID requestID = UUID.randomUUID(); + Collection<PolicyConfig> 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<String> getDecision(PolicyEngine policyEngine, + String eCOMPComponentName, Map<String, String> decisionAttributes) { + ArrayList<String> resultReceived = new ArrayList<String>(); + // 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<String> getAction(PolicyEngine policyEngine, + Map<String, String> eventAttributes) { + ArrayList<String> resultReceived = new ArrayList<String>(); + try { + UUID requestID = UUID.randomUUID(); + 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) { +// 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()); + + } + + } + +} |