Add APPC LCM Interface
[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.yaml.snakeyaml.Yaml;
39 import org.yaml.snakeyaml.constructor.Constructor;
40 import org.kie.api.KieServices;
41 import org.kie.api.builder.KieBuilder;
42 import org.kie.api.builder.KieFileSystem;
43 import org.kie.api.builder.Message;
44 import org.kie.api.builder.ReleaseId;
45 import org.kie.api.builder.Results;
46 import org.kie.api.builder.model.KieModuleModel;
47 import org.kie.api.runtime.KieContainer;
48 import org.kie.api.runtime.KieSession;
49 import org.onap.policy.controlloop.ControlLoopLogger;
50 import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl;
51 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
52 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
53 import org.onap.policy.drools.http.server.HttpServletServer;
54 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
55 import org.onap.policy.guard.PolicyGuardYamlToXacml;
56
57 import com.att.research.xacml.api.pdp.PDPEngine;
58 import com.att.research.xacml.api.pdp.PDPEngineFactory;
59 import com.att.research.xacml.util.FactoryException;
60 import com.att.research.xacml.util.XACMLProperties;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 public final class Util {
65
66         private static final Logger logger = LoggerFactory.getLogger(Util.class);
67         public static class Pair<A, B> {
68                 public final A a;
69                 public final B b;
70                 
71                 public Pair(A a, B b) {
72                         this.a = a;
73                         this.b = b;
74                 }
75         }
76         
77         public static Pair<ControlLoopPolicy, String>   loadYaml(String testFile) {
78                 try (InputStream is = new FileInputStream(new File(testFile))) {
79                         String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
80                         //
81                         // Read the yaml into our Java Object
82                         //
83                         Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
84                         Object obj = yaml.load(contents);
85                         
86                         //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas");
87                         logger.debug(contents);
88                         //for(Policy policy : ((ControlLoopPolicy)obj).policies){
89                         
90                         return new Pair<ControlLoopPolicy, String>((ControlLoopPolicy) obj, contents);
91                 } catch (FileNotFoundException e) {
92                         fail(e.getLocalizedMessage());
93                 } catch (IOException e) {
94                         fail(e.getLocalizedMessage());
95                 }
96                 return null;
97         }
98         
99         public static ControlLoopGuard  loadYamlGuard(String testFile) {
100                 try (InputStream is = new FileInputStream(new File(testFile))) {
101                         String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
102                         //
103                         // Read the yaml into our Java Object
104                         //
105                         Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class));
106                         Object obj = yaml.load(contents);
107                         return (ControlLoopGuard) obj;
108                 } catch (FileNotFoundException e) {
109                         fail(e.getLocalizedMessage());
110                 } catch (IOException e) {
111                         fail(e.getLocalizedMessage());
112                 }
113                 return null;
114         }
115         
116         public static HttpServletServer buildAaiSim() throws InterruptedException {
117                 HttpServletServer testServer = HttpServletServer.factory.build("testServer", "localhost", 6666, "/", false, true);
118                 testServer.addServletClass("/*", AaiSimulator.class.getName());
119                 testServer.waitedStart(5000);
120                 return testServer;
121         }
122         
123         public static HttpServletServer buildMsoSim() throws InterruptedException {
124                 HttpServletServer testServer = HttpServletServer.factory.build("testServer", "localhost", 6667, "/", false, true);
125                 testServer.addServletClass("/*", MsoSimulatorJaxRs.class.getName());
126                 testServer.waitedStart(5000);
127                 return testServer;
128         }
129         
130         public static HttpServletServer buildVfcSim() throws InterruptedException {
131                 HttpServletServer testServer = HttpServletServer.factory.build("testServer", "localhost", 6668, "/", false, true);
132                 testServer.addServletClass("/*", VfcSimulatorJaxRs.class.getName());
133                 testServer.waitedStart(5000);
134                 return testServer;
135         }
136         
137         private static String   generatePolicy(String ruleContents, 
138                         String closedLoopControlName, 
139                         String policyScope, 
140                         String policyName, 
141                         String policyVersion, 
142                         String controlLoopYaml) {
143
144                 Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}");
145                 Matcher m = p.matcher(ruleContents);
146                 ruleContents = m.replaceAll(closedLoopControlName);
147
148                 p = Pattern.compile("\\$\\{policyScope\\}");
149                 m = p.matcher(ruleContents);
150                 ruleContents = m.replaceAll(policyScope);
151
152                 p = Pattern.compile("\\$\\{policyName\\}");
153                 m = p.matcher(ruleContents);
154                 ruleContents = m.replaceAll(policyName);
155
156                 p = Pattern.compile("\\$\\{policyVersion\\}");
157                 m = p.matcher(ruleContents);
158                 ruleContents = m.replaceAll(policyVersion);
159
160                 p = Pattern.compile("\\$\\{controlLoopYaml\\}");
161                 m = p.matcher(ruleContents);
162                 ruleContents = m.replaceAll(controlLoopYaml);
163
164                 return ruleContents;
165         }
166
167         public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, String policyScope, String policyName, String policyVersion, String yamlSpecification) throws IOException {
168                 //
169         // Get our Drools Kie factory
170         //
171         KieServices ks = KieServices.Factory.get();
172         
173         KieModuleModel kModule = ks.newKieModuleModel();
174         
175         logger.debug("KMODULE:" + System.lineSeparator() + kModule.toXML());
176         
177         //
178         // Generate our drools rule from our template
179         //
180         KieFileSystem kfs = ks.newKieFileSystem();
181         
182         kfs.writeKModuleXML(kModule.toXML());
183         {
184                 Path rule = Paths.get(droolsTemplate);
185                 String ruleTemplate = new String(Files.readAllBytes(rule));
186                 String drlContents = generatePolicy(ruleTemplate,
187                                                                 closedLoopControlName,
188                                                                 policyScope,
189                                                                         policyName,
190                                                                         policyVersion,
191                                                                         yamlSpecification);
192                 
193                 kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes()));
194         }
195         //
196         // Compile the rule
197         //
198         KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
199         Results results = builder.getResults();
200         if (results.hasMessages(Message.Level.ERROR)) {
201                 for (Message msg : results.getMessages()) {
202                         logger.error(msg.toString());
203                 }
204                 throw new RuntimeException("Drools Rule has Errors");
205         }
206         for (Message msg : results.getMessages()) {
207                 logger.debug(msg.toString());
208         }
209         //
210         // Create our kie Session and container
211         //
212         ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
213         logger.debug(releaseId.toString());
214             KieContainer kContainer = ks.newKieContainer(releaseId);
215             
216             return setupSession(kContainer.newKieSession());
217         }
218         
219         private static KieSession setupSession (KieSession kieSession) {
220
221                 
222                 //
223                 // Create XACML Guard policy from YAML
224                 // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm)
225                 //
226                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_restart.yaml", 
227                                                 "src/main/resources/frequency_limiter_template.xml", 
228                                                 "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml");
229                 
230                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild.yaml", 
231                                                 "src/main/resources/frequency_limiter_template.xml", 
232                                                 "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml");
233                 
234                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml", 
235                                                 "src/main/resources/frequency_limiter_template.xml", 
236                                                 "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml");
237                 
238                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_migrate.yaml", 
239                                                 "src/main/resources/frequency_limiter_template.xml", 
240                                                 "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml");
241                 
242                 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_modifyconfig.yaml", 
243                 "src/main/resources/frequency_limiter_template.xml", 
244                 "src/test/resources/xacml/autogenerated_frequency_limiter_modifyconfig.xml");
245                 
246                 PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist("src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml", 
247                                                                                                                 "src/main/resources/blacklist_template.xml", 
248                                                                                                                 "src/test/resources/xacml/autogenerated_blacklist.xml");
249
250         
251                 //
252                 // Insert our globals
253                 //
254                 final ControlLoopLogger controlLoopLogger = new ControlLoopLoggerStdOutImpl();
255                 kieSession.setGlobal("Logger", controlLoopLogger);
256                 final PolicyEngineJUnitImpl engine = new PolicyEngineJUnitImpl();
257                 kieSession.setGlobal("Engine", engine);
258                 
259                 
260                 //
261                 // Creating an embedded XACML PDP
262                 //
263                 final PDPEngine xacmlPdpEngine;
264                 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties");
265                 
266                 PDPEngineFactory factory;
267                 try {
268                         factory = PDPEngineFactory.newInstance();
269                         xacmlPdpEngine = factory.newEngine();
270                         kieSession.setGlobal("XacmlPdpEngine", xacmlPdpEngine);
271                 } catch (FactoryException e1) {
272                         e1.printStackTrace();
273                 }
274                 return kieSession;
275         }
276
277 }