Merge "Fix major sonar issues"
[policy/drools-applications.git] / controlloop / templates / template.demo / src / test / java / org / onap / policy / template / demo / Util.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.template.demo;
22
23 import static org.junit.Assert.fail;
24
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.nio.charset.StandardCharsets;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36
37 import org.apache.commons.io.IOUtils;
38 import org.kie.api.KieServices;
39 import org.kie.api.builder.KieBuilder;
40 import org.kie.api.builder.KieFileSystem;
41 import org.kie.api.builder.Message;
42 import org.kie.api.builder.ReleaseId;
43 import org.kie.api.builder.Results;
44 import org.kie.api.builder.model.KieModuleModel;
45 import org.kie.api.runtime.KieContainer;
46 import org.kie.api.runtime.KieSession;
47 import org.onap.policy.controlloop.ControlLoopLogger;
48 import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl;
49 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
50 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
51 import org.onap.policy.drools.http.server.HttpServletServer;
52 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
53 import org.onap.policy.drools.system.PolicyEngine;
54 import org.onap.policy.guard.PolicyGuardYamlToXacml;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.yaml.snakeyaml.Yaml;
58 import org.yaml.snakeyaml.constructor.Constructor;
59
60 import com.att.research.xacml.api.pdp.PDPEngine;
61 import com.att.research.xacml.api.pdp.PDPEngineFactory;
62 import com.att.research.xacml.util.FactoryException;
63 import com.att.research.xacml.util.XACMLProperties;
64
65 public final class Util {
66
67         private static final Logger logger = LoggerFactory.getLogger(Util.class);
68         public static class Pair<A, B> {
69                 public final A a;
70                 public final B b;
71                 
72                 public Pair(A a, B b) {
73                         this.a = a;
74                         this.b = b;
75                 }
76         }
77         
78         public static Pair<ControlLoopPolicy, String>   loadYaml(String testFile) {
79                 try (InputStream is = new FileInputStream(new File(testFile))) {
80                         String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
81                         //
82                         // Read the yaml into our Java Object
83                         //
84                         Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
85                         Object obj = yaml.load(contents);
86                         
87                         //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas");
88                         logger.debug(contents);
89                         //for(Policy policy : ((ControlLoopPolicy)obj).policies){
90                         
91                         return new Pair<ControlLoopPolicy, String>((ControlLoopPolicy) obj, contents);
92                 } catch (FileNotFoundException e) {
93                         fail(e.getLocalizedMessage());
94                 } catch (IOException e) {
95                         fail(e.getLocalizedMessage());
96                 }
97                 return null;
98         }
99         
100         public static ControlLoopGuard  loadYamlGuard(String testFile) {
101                 try (InputStream is = new FileInputStream(new File(testFile))) {
102                         String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
103                         //
104                         // Read the yaml into our Java Object
105                         //
106                         Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class));
107                         Object obj = yaml.load(contents);
108                         return (ControlLoopGuard) obj;
109                 } catch (FileNotFoundException e) {
110                         fail(e.getLocalizedMessage());
111                 } catch (IOException e) {
112                         fail(e.getLocalizedMessage());
113                 }
114                 return null;
115         }
116         
117         public static HttpServletServer buildAaiSim() throws InterruptedException, IOException {
118                 return org.onap.policy.simulators.Util.buildAaiSim();
119         }
120         
121         public static HttpServletServer buildSoSim() throws InterruptedException, IOException {
122                 return org.onap.policy.simulators.Util.buildSoSim();
123         }
124         
125         public static HttpServletServer buildVfcSim() throws InterruptedException, IOException {
126                 return org.onap.policy.simulators.Util.buildVfcSim();
127         }
128         
129         public static HttpServletServer buildGuardSim() throws InterruptedException, IOException {
130         return org.onap.policy.simulators.Util.buildGuardSim();
131     }
132         
133         private static String   generatePolicy(String ruleContents, 
134                         String closedLoopControlName, 
135                         String policyScope, 
136                         String policyName, 
137                         String policyVersion, 
138                         String controlLoopYaml) {
139
140                 Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}");
141                 Matcher m = p.matcher(ruleContents);
142                 ruleContents = m.replaceAll(closedLoopControlName);
143
144                 p = Pattern.compile("\\$\\{policyScope\\}");
145                 m = p.matcher(ruleContents);
146                 ruleContents = m.replaceAll(policyScope);
147
148                 p = Pattern.compile("\\$\\{policyName\\}");
149                 m = p.matcher(ruleContents);
150                 ruleContents = m.replaceAll(policyName);
151
152                 p = Pattern.compile("\\$\\{policyVersion\\}");
153                 m = p.matcher(ruleContents);
154                 ruleContents = m.replaceAll(policyVersion);
155
156                 p = Pattern.compile("\\$\\{controlLoopYaml\\}");
157                 m = p.matcher(ruleContents);
158                 ruleContents = m.replaceAll(controlLoopYaml);
159
160                 return ruleContents;
161         }
162
163         public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, String policyScope, String policyName, String policyVersion, String yamlSpecification) throws IOException {
164                 //
165         // Get our Drools Kie factory
166         //
167         KieServices ks = KieServices.Factory.get();
168         
169         KieModuleModel kModule = ks.newKieModuleModel();
170         
171         logger.debug("KMODULE:" + System.lineSeparator() + kModule.toXML());
172         
173         //
174         // Generate our drools rule from our template
175         //
176         KieFileSystem kfs = ks.newKieFileSystem();
177         
178         kfs.writeKModuleXML(kModule.toXML());
179         {
180                 Path rule = Paths.get(droolsTemplate);
181                 String ruleTemplate = new String(Files.readAllBytes(rule));
182                 String drlContents = generatePolicy(ruleTemplate,
183                                                                 closedLoopControlName,
184                                                                 policyScope,
185                                                                         policyName,
186                                                                         policyVersion,
187                                                                         yamlSpecification);
188                 
189                 kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes()));
190         }
191         //
192         // Compile the rule
193         //
194         KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
195         Results results = builder.getResults();
196         if (results.hasMessages(Message.Level.ERROR)) {
197                 for (Message msg : results.getMessages()) {
198                         logger.error(msg.toString());
199                 }
200                 throw new RuntimeException("Drools Rule has Errors");
201         }
202         for (Message msg : results.getMessages()) {
203                 logger.debug(msg.toString());
204         }
205         //
206         // Create our kie Session and container
207         //
208         ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
209         logger.debug(releaseId.toString());
210             KieContainer kContainer = ks.newKieContainer(releaseId);
211             
212             return setupSession(kContainer.newKieSession());
213         }
214         
215         private static KieSession setupSession (KieSession kieSession) {
216
217                 
218                 //
219                 // Create XACML Guard policy from YAML
220                 // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm)
221                 //
222                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_restart.yaml", 
223                                                 "src/main/resources/frequency_limiter_template.xml", 
224                                                 "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml");
225                 
226                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild.yaml", 
227                                                 "src/main/resources/frequency_limiter_template.xml", 
228                                                 "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml");
229                 
230                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml", 
231                                                 "src/main/resources/frequency_limiter_template.xml", 
232                                                 "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml");
233                 
234                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_migrate.yaml", 
235                                                 "src/main/resources/frequency_limiter_template.xml", 
236                                                 "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml");
237                 
238                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_modifyconfig.yaml", 
239                 "src/main/resources/frequency_limiter_template.xml", 
240                 "src/test/resources/xacml/autogenerated_frequency_limiter_modifyconfig.xml");
241                 
242                 PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist("src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml", 
243                                                                                                                 "src/main/resources/blacklist_template.xml", 
244                                                                                                                 "src/test/resources/xacml/autogenerated_blacklist.xml");
245
246         
247                 //
248                 // Insert our globals
249                 //
250                 final ControlLoopLogger controlLoopLogger = new ControlLoopLoggerStdOutImpl();
251                 kieSession.setGlobal("Logger", controlLoopLogger);
252                 final PolicyEngineJUnitImpl engine = new PolicyEngineJUnitImpl();
253                 kieSession.setGlobal("Engine", engine);
254                 
255                 
256                 //
257                 // Creating an embedded XACML PDP
258                 //
259                 final PDPEngine xacmlPdpEngine;
260                 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties");
261                 
262                 PDPEngineFactory factory;
263                 try {
264                         factory = PDPEngineFactory.newInstance();
265                         xacmlPdpEngine = factory.newEngine();
266                         kieSession.setGlobal("XacmlPdpEngine", xacmlPdpEngine);
267                 } catch (FactoryException e1) {
268                         e1.printStackTrace();
269                 }
270                 return kieSession;
271         }
272         
273         public static void setAAIProps(){
274                 PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666");
275         PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI");
276         PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI");
277         }
278         public static void setSOProps(){
279                 PolicyEngine.manager.setEnvironmentProperty("so.url", "http://localhost:6667");
280         PolicyEngine.manager.setEnvironmentProperty("so.username", "SO");
281         PolicyEngine.manager.setEnvironmentProperty("so.password", "SO");
282         }
283
284 }