2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.template.demo;
23 import static org.junit.Assert.fail;
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;
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;
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;
64 public final class Util {
66 private static final Logger logger = LoggerFactory.getLogger(Util.class);
67 public static class Pair<A, B> {
71 public Pair(A a, B b) {
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);
81 // Read the yaml into our Java Object
83 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
84 Object obj = yaml.load(contents);
86 //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas");
87 logger.debug(contents);
88 //for(Policy policy : ((ControlLoopPolicy)obj).policies){
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());
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);
103 // Read the yaml into our Java Object
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());
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);
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);
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);
137 private static String generatePolicy(String ruleContents,
138 String closedLoopControlName,
141 String policyVersion,
142 String controlLoopYaml) {
144 Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}");
145 Matcher m = p.matcher(ruleContents);
146 ruleContents = m.replaceAll(closedLoopControlName);
148 p = Pattern.compile("\\$\\{policyScope\\}");
149 m = p.matcher(ruleContents);
150 ruleContents = m.replaceAll(policyScope);
152 p = Pattern.compile("\\$\\{policyName\\}");
153 m = p.matcher(ruleContents);
154 ruleContents = m.replaceAll(policyName);
156 p = Pattern.compile("\\$\\{policyVersion\\}");
157 m = p.matcher(ruleContents);
158 ruleContents = m.replaceAll(policyVersion);
160 p = Pattern.compile("\\$\\{controlLoopYaml\\}");
161 m = p.matcher(ruleContents);
162 ruleContents = m.replaceAll(controlLoopYaml);
167 public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, String policyScope, String policyName, String policyVersion, String yamlSpecification) throws IOException {
169 // Get our Drools Kie factory
171 KieServices ks = KieServices.Factory.get();
173 KieModuleModel kModule = ks.newKieModuleModel();
175 logger.debug("KMODULE:" + System.lineSeparator() + kModule.toXML());
178 // Generate our drools rule from our template
180 KieFileSystem kfs = ks.newKieFileSystem();
182 kfs.writeKModuleXML(kModule.toXML());
184 Path rule = Paths.get(droolsTemplate);
185 String ruleTemplate = new String(Files.readAllBytes(rule));
186 String drlContents = generatePolicy(ruleTemplate,
187 closedLoopControlName,
193 kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes()));
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());
204 throw new RuntimeException("Drools Rule has Errors");
206 for (Message msg : results.getMessages()) {
207 logger.debug(msg.toString());
210 // Create our kie Session and container
212 ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
213 logger.debug(releaseId.toString());
214 KieContainer kContainer = ks.newKieContainer(releaseId);
216 return setupSession(kContainer.newKieSession());
219 private static KieSession setupSession (KieSession kieSession) {
223 // Create XACML Guard policy from YAML
224 // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm)
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");
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");
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");
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");
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");
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");
252 // Insert our globals
254 final ControlLoopLogger controlLoopLogger = new ControlLoopLoggerStdOutImpl();
255 kieSession.setGlobal("Logger", controlLoopLogger);
256 final PolicyEngineJUnitImpl engine = new PolicyEngineJUnitImpl();
257 kieSession.setGlobal("Engine", engine);
261 // Creating an embedded XACML PDP
263 final PDPEngine xacmlPdpEngine;
264 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties");
266 PDPEngineFactory factory;
268 factory = PDPEngineFactory.newInstance();
269 xacmlPdpEngine = factory.newEngine();
270 kieSession.setGlobal("XacmlPdpEngine", xacmlPdpEngine);
271 } catch (FactoryException e1) {
272 e1.printStackTrace();