Fix build issues in drools-applications due to changes in policy/models repo
[policy/drools-applications.git] / controlloop / common / guard / src / main / java / org / onap / policy / guard / PolicyGuardYamlToXacml.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * guard
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.guard;
22
23 import java.io.IOException;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.util.List;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30
31 import org.onap.policy.controlloop.policy.guard.Constraint;
32 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
33 import org.onap.policy.controlloop.policy.guard.GuardPolicy;
34 import org.onap.policy.controlloop.policy.guard.MatchParameters;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 public class PolicyGuardYamlToXacml {
39     private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class);
40
41     private PolicyGuardYamlToXacml() {
42         // Construction of this static class is not allowed
43     }
44
45     /**
46      * Convert from Yaml to Xacml.
47      * 
48      * @param yamlFile the Yaml file
49      * @param xacmlTemplate the Xacml template
50      * @param xacmlPolicyOutput the Xacml output
51      */
52     public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) {
53         ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile);
54         GuardPolicy guardPolicy = yamlGuardObject.getGuards().get(0);
55         logger.debug("clname: {}", guardPolicy.getMatch_parameters().getControlLoopName());
56         logger.debug("actor: {}", guardPolicy.getMatch_parameters().getActor());
57         logger.debug("recipe: {}", guardPolicy.getMatch_parameters().getRecipe());
58         Constraint constraint = guardPolicy.getLimit_constraints().get(0);
59         logger.debug("num: {}", constraint.getFreq_limit_per_target());
60         logger.debug("duration: {}", constraint.getTime_window());
61         logger.debug("time_in_range: {}", constraint.getActive_time_range());
62
63         Path xacmlTemplatePath = Paths.get(xacmlTemplate);
64         String xacmlTemplateContent;
65
66         try {
67             xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
68
69             String xacmlPolicyContent = generateXacmlGuard(xacmlTemplateContent,
70                     guardPolicy.getMatch_parameters(), constraint);
71
72             Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
73
74         } catch (IOException e) {
75             logger.error("fromYamlToXacml threw: ", e);
76         }
77     }
78
79     /**
80      * Generate a Xacml guard.
81      * 
82      * @param xacmlTemplateContent the Xacml template content
83      * @param matchParameters the paremeters to use
84      * @param constraint the constraint to use
85      * @return the guard
86      */
87     private static String generateXacmlGuard(String xacmlTemplateContent, MatchParameters matchParameters,
88             Constraint constraint) {
89         Pattern pattern = Pattern.compile("\\$\\{clname\\}");
90         Matcher matcher = pattern.matcher(xacmlTemplateContent);
91         if (isNullOrEmpty(matchParameters.getControlLoopName())) {
92             matchParameters.setControlLoopName(".*");
93         }
94         xacmlTemplateContent = matcher.replaceAll(matchParameters.getControlLoopName());
95
96         pattern = Pattern.compile("\\$\\{actor\\}");
97         matcher = pattern.matcher(xacmlTemplateContent);
98         if (isNullOrEmpty(matchParameters.getActor())) {
99             matchParameters.setActor(".*");
100         }
101         xacmlTemplateContent = matcher.replaceAll(matchParameters.getActor());
102
103         pattern = Pattern.compile("\\$\\{recipe\\}");
104         matcher = pattern.matcher(xacmlTemplateContent);
105         if (isNullOrEmpty(matchParameters.getRecipe())) {
106             matchParameters.setRecipe(".*");
107         }
108         xacmlTemplateContent = matcher.replaceAll(matchParameters.getRecipe());
109
110         pattern = Pattern.compile("\\$\\{targets\\}");
111         matcher = pattern.matcher(xacmlTemplateContent);
112         String targetsRegex = "";
113         if (isNullOrEmptyList(matchParameters.getTargets())) {
114             targetsRegex = ".*";
115         } else {
116             StringBuilder targetsRegexSb = new StringBuilder();
117             boolean addBarChar = false;
118             for (String t : matchParameters.getTargets()) {
119                 targetsRegexSb.append(t);
120                 if (addBarChar) {
121                     targetsRegexSb.append("|");
122                 } else {
123                     addBarChar = true;
124                 }
125             }
126             targetsRegex = targetsRegexSb.toString();
127         }
128         xacmlTemplateContent = matcher.replaceAll(targetsRegex);
129
130         pattern = Pattern.compile("\\$\\{limit\\}");
131         matcher = pattern.matcher(xacmlTemplateContent);
132         xacmlTemplateContent = matcher.replaceAll(constraint.getFreq_limit_per_target().toString());
133
134         pattern = Pattern.compile("\\$\\{twValue\\}");
135         matcher = pattern.matcher(xacmlTemplateContent);
136         xacmlTemplateContent = matcher.replaceAll(constraint.getTime_window().get("value"));
137
138         pattern = Pattern.compile("\\$\\{twUnits\\}");
139         matcher = pattern.matcher(xacmlTemplateContent);
140         xacmlTemplateContent = matcher.replaceAll(constraint.getTime_window().get("units"));
141
142
143         pattern = Pattern.compile("\\$\\{guardActiveStart\\}");
144         matcher = pattern.matcher(xacmlTemplateContent);
145         xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("start"));
146
147         pattern = Pattern.compile("\\$\\{guardActiveEnd\\}");
148         matcher = pattern.matcher(xacmlTemplateContent);
149         xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("end"));
150         logger.debug(xacmlTemplateContent);
151
152         return xacmlTemplateContent;
153     }
154
155     public static boolean isNullOrEmpty(String string) {
156         return string == null || string.trim().isEmpty();
157     }
158
159     public static boolean isNullOrEmptyList(List<String> list) {
160         return list == null || list.isEmpty();
161     }
162
163     /**
164      * Convert from Yaml to Xacml blacklist.
165      * 
166      * @param yamlFile the Yaml file
167      * @param xacmlTemplate the Xacml template
168      * @param xacmlPolicyOutput the Xacml output
169      */
170     public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) {
171         ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile);
172         GuardPolicy guardPolicy = yamlGuardObject.getGuards().get(0);
173         logger.debug("actor: {}", guardPolicy.getMatch_parameters().getActor());
174         logger.debug("recipe: {}", guardPolicy.getMatch_parameters().getRecipe());
175         Constraint constraint = guardPolicy.getLimit_constraints().get(0);
176         logger.debug("freq_limit_per_target: {}", constraint.getFreq_limit_per_target());
177         logger.debug("time_window: {}", constraint.getTime_window());
178         logger.debug("active_time_range: {}", constraint.getActive_time_range());
179
180         Path xacmlTemplatePath = Paths.get(xacmlTemplate);
181         String xacmlTemplateContent;
182
183         try {
184             xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
185             String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent,
186                     guardPolicy.getMatch_parameters(), constraint);
187
188             Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
189
190         } catch (IOException e) {
191             logger.error("fromYamlToXacmlBlacklist threw: ", e);
192         }
193     }
194
195     private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters,
196             Constraint constraint) {
197         Pattern pattern = Pattern.compile("\\$\\{clname\\}");
198         Matcher matcher = pattern.matcher(xacmlTemplateContent);
199         if (isNullOrEmpty(matchParameters.getControlLoopName())) {
200             matchParameters.setControlLoopName(".*");
201         }
202         xacmlTemplateContent = matcher.replaceAll(matchParameters.getControlLoopName());
203
204         pattern = Pattern.compile("\\$\\{actor\\}");
205         matcher = pattern.matcher(xacmlTemplateContent);
206         if (isNullOrEmpty(matchParameters.getActor())) {
207             matchParameters.setActor(".*");
208         }
209         xacmlTemplateContent = matcher.replaceAll(matchParameters.getActor());
210
211         pattern = Pattern.compile("\\$\\{recipe\\}");
212         matcher = pattern.matcher(xacmlTemplateContent);
213         if (isNullOrEmpty(matchParameters.getRecipe())) {
214             matchParameters.setRecipe(".*");
215         }
216         xacmlTemplateContent = matcher.replaceAll(matchParameters.getRecipe());
217
218         pattern = Pattern.compile("\\$\\{guardActiveStart\\}");
219         matcher = pattern.matcher(xacmlTemplateContent);
220         xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("start"));
221
222         pattern = Pattern.compile("\\$\\{guardActiveEnd\\}");
223         matcher = pattern.matcher(xacmlTemplateContent);
224         xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("end"));
225         logger.debug(xacmlTemplateContent);
226
227         for (String target : constraint.getBlacklist()) {
228             pattern = Pattern.compile("\\$\\{blackListElement\\}");
229             matcher = pattern.matcher(xacmlTemplateContent);
230             xacmlTemplateContent =
231                     matcher.replaceAll("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + target
232                             + "</AttributeValue>" + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}\n");
233         }
234
235         pattern = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n");
236         matcher = pattern.matcher(xacmlTemplateContent);
237         xacmlTemplateContent = matcher.replaceAll("");
238
239
240         return xacmlTemplateContent;
241     }
242 }