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