Fix sonar issues in drools-applications
[policy/drools-applications.git] / controlloop / common / guard / src / main / java / org / onap / policy / guard / PolicyGuardYamlToXacml.java
index baf43b3..057c3f1 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * guard
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,237 +24,181 @@ import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.util.LinkedList;
 import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-
+import java.util.function.Consumer;
+import org.onap.policy.controlloop.policy.guard.Constraint;
 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
-
-
+import org.onap.policy.controlloop.policy.guard.GuardPolicy;
+import org.onap.policy.controlloop.policy.guard.MatchParameters;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class PolicyGuardYamlToXacml {
-       
-       
-       public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){
-               
-               ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile);
-               System.out.println("clname: " + yamlGuardObject.guards.getFirst().match_parameters.controlLoopName);
-               System.out.println("actor: " + yamlGuardObject.guards.getFirst().match_parameters.actor);
-               System.out.println("recipe: " + yamlGuardObject.guards.getFirst().match_parameters.recipe);
-               System.out.println("num: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().freq_limit_per_target);
-               System.out.println("duration: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_window);
-               System.out.println("time_in_range: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range);
-               
-               Path xacmlTemplatePath = Paths.get(xacmlTemplate);
+    private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class);
+
+    private PolicyGuardYamlToXacml() {
+        // Construction of this static class is not allowed
+    }
+
+    /**
+     * Convert from Yaml to Xacml.
+     *
+     * @param yamlFile the Yaml file
+     * @param xacmlTemplate the Xacml template
+     * @param xacmlPolicyOutput the Xacml output
+     */
+    public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) {
+        ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile);
+        GuardPolicy guardPolicy = yamlGuardObject.getGuards().get(0);
+        logger.debug("clname: {}", guardPolicy.getMatch_parameters().getControlLoopName());
+        logger.debug("actor: {}", guardPolicy.getMatch_parameters().getActor());
+        logger.debug("recipe: {}", guardPolicy.getMatch_parameters().getRecipe());
+        Constraint constraint = guardPolicy.getLimit_constraints().get(0);
+        logger.debug("num: {}", constraint.getFreq_limit_per_target());
+        logger.debug("duration: {}", constraint.getTime_window());
+        logger.debug("time_in_range: {}", constraint.getActive_time_range());
+
+        Path xacmlTemplatePath = Paths.get(xacmlTemplate);
         String xacmlTemplateContent;
-               
+
         try {
-                       xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
-                       
-               String xacmlPolicyContent = generateXacmlGuard(xacmlTemplateContent,
-                               yamlGuardObject.guards.getFirst().match_parameters.controlLoopName,
-                               yamlGuardObject.guards.getFirst().match_parameters.actor,
-                               yamlGuardObject.guards.getFirst().match_parameters.recipe,
-                               yamlGuardObject.guards.getFirst().match_parameters.targets,
-                               yamlGuardObject.guards.getFirst().limit_constraints.getFirst().freq_limit_per_target,
-                               yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_window,
-                               yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range.get("start"),
-                               yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range.get("end")
-                               );
-               
-       
-               Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
-        
-               } catch (IOException e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
-               }
-               
-       }
-       
-       
-       
-       public static String    generateXacmlGuard(String xacmlFileContent, 
-                       String clname,
-                       String actor, 
-                       String recipe,
-                       LinkedList<String> targets,
-                       Integer limit,
-                       Map<String,String> timeWindow,
-                       String guardActiveStart, 
-                       String guardActiveEnd) {
-
-               Pattern p = Pattern.compile("\\$\\{clname\\}");
-               Matcher m = p.matcher(xacmlFileContent);
-               if(isNullOrEmpty(clname)) clname = ".*";
-               xacmlFileContent = m.replaceAll(clname);
-               
-               p = Pattern.compile("\\$\\{actor\\}");
-               m = p.matcher(xacmlFileContent);
-               if(isNullOrEmpty(actor)) actor = ".*";
-               xacmlFileContent = m.replaceAll(actor);
-
-               p = Pattern.compile("\\$\\{recipe\\}");
-               m = p.matcher(xacmlFileContent);
-               if(isNullOrEmpty(recipe)) recipe = ".*";
-               xacmlFileContent = m.replaceAll(recipe);
-               
-               p = Pattern.compile("\\$\\{targets\\}");
-               m = p.matcher(xacmlFileContent);
-               String targetsRegex = "";
-               if(isNullOrEmptyList(targets)){ 
-                       targetsRegex = ".*";
-               }
-               else{
-                       for(String t : targets){
-                               targetsRegex += (t + "|");
-                               
-                       }
-                       targetsRegex = targetsRegex.substring(0, targetsRegex.length()-1);
-               }
-               xacmlFileContent = m.replaceAll(targetsRegex);
-
-               p = Pattern.compile("\\$\\{limit\\}");
-               m = p.matcher(xacmlFileContent);
-               xacmlFileContent = m.replaceAll(limit.toString());
-               
-               
-               //p = Pattern.compile("\\$\\{timeWindow\\}");
-               //m = p.matcher(xacmlFileContent);
-               //xacmlFileContent = m.replaceAll("tw"+timeWindow);
-               
-               p = Pattern.compile("\\$\\{twValue\\}");
-               m = p.matcher(xacmlFileContent);
-               xacmlFileContent = m.replaceAll(timeWindow.get("value"));
-               
-               p = Pattern.compile("\\$\\{twUnits\\}");
-               m = p.matcher(xacmlFileContent);
-               xacmlFileContent = m.replaceAll(timeWindow.get("units"));
-               
-
-               p = Pattern.compile("\\$\\{guardActiveStart\\}");
-               m = p.matcher(xacmlFileContent);
-               xacmlFileContent = m.replaceAll(guardActiveStart);
-
-               p = Pattern.compile("\\$\\{guardActiveEnd\\}");
-               m = p.matcher(xacmlFileContent);
-               xacmlFileContent = m.replaceAll(guardActiveEnd);
-               System.out.println(xacmlFileContent);
-
-               return xacmlFileContent;
-       }
-       
-       public static boolean isNullOrEmpty(String s){
-               
-               if(s == null){
-                       return true;
-               }
-               else if(s.equals("")){
-                       return true;
-               }
-               return false;
-               
-       }
-       
-       public static boolean isNullOrEmptyList(LinkedList<String> list){
-               
-               if(list == null){
-                       return true;
-               }
-               else if(list.isEmpty()){
-                       return true;
-               }
-               return false;
-               
-       }
-
-       
-       public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){
-               
-               ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile);
-               System.out.println("actor: " + yamlGuardObject.guards.getFirst().match_parameters.actor);
-               System.out.println("recipe: " + yamlGuardObject.guards.getFirst().match_parameters.recipe);
-               System.out.println("freq_limit_per_target: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().freq_limit_per_target);
-               System.out.println("time_window: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_window);
-               System.out.println("active_time_range: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range);
-               
-               Path xacmlTemplatePath = Paths.get(xacmlTemplate);
+            xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
+
+            String xacmlPolicyContent = generateXacmlGuard(xacmlTemplateContent,
+                    guardPolicy.getMatch_parameters(), constraint);
+
+            Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
+
+        } catch (IOException e) {
+            logger.error("fromYamlToXacml threw: ", e);
+        }
+    }
+
+    /**
+     * Generate a Xacml guard.
+     *
+     * @param xacmlTemplateContent the Xacml template content
+     * @param matchParameters the paremeters to use
+     * @param constraint the constraint to use
+     * @return the guard
+     */
+    private static String generateXacmlGuard(String xacmlTemplateContent, MatchParameters matchParameters,
+            Constraint constraint) {
+
+        xacmlTemplateContent = doCommonReplacements(xacmlTemplateContent, matchParameters, constraint);
+
+        String targetsRegex = "";
+        if (isNullOrEmptyList(matchParameters.getTargets())) {
+            targetsRegex = ".*";
+        } else {
+            StringBuilder targetsRegexSb = new StringBuilder();
+            boolean addBarChar = false;
+            for (String t : matchParameters.getTargets()) {
+                targetsRegexSb.append(t);
+                if (addBarChar) {
+                    targetsRegexSb.append("|");
+                } else {
+                    addBarChar = true;
+                }
+            }
+            targetsRegex = targetsRegexSb.toString();
+        }
+        xacmlTemplateContent = xacmlTemplateContent.replace("${targets}", targetsRegex);
+
+        xacmlTemplateContent = xacmlTemplateContent.replace("${limit}",
+                        constraint.getFreq_limit_per_target().toString());
+
+        xacmlTemplateContent = xacmlTemplateContent.replace("${twValue}", constraint.getTime_window().get("value"));
+
+        xacmlTemplateContent = xacmlTemplateContent.replace("${twUnits}", constraint.getTime_window().get("units"));
+
+        logger.debug(xacmlTemplateContent);
+
+        return xacmlTemplateContent;
+    }
+
+    private static String doCommonReplacements(String xacmlTemplateContent, MatchParameters matchParameters,
+                    Constraint constraint) {
+
+        replaceNullOrEmpty(matchParameters.getControlLoopName(), matchParameters::setControlLoopName, ".*");
+        xacmlTemplateContent = xacmlTemplateContent.replace("${clname}", matchParameters.getControlLoopName());
+
+        replaceNullOrEmpty(matchParameters.getActor(), matchParameters::setActor, ".*");
+        xacmlTemplateContent = xacmlTemplateContent.replace("${actor}", matchParameters.getActor());
+
+        replaceNullOrEmpty(matchParameters.getRecipe(), matchParameters::setRecipe, ".*");
+        xacmlTemplateContent = xacmlTemplateContent.replace("${recipe}", matchParameters.getRecipe());
+
+        xacmlTemplateContent = xacmlTemplateContent.replace("${guardActiveStart}",
+                        constraint.getActive_time_range().get("start"));
+
+        xacmlTemplateContent = xacmlTemplateContent.replace("${guardActiveEnd}",
+                        constraint.getActive_time_range().get("end"));
+
+        return xacmlTemplateContent;
+    }
+
+    private static void replaceNullOrEmpty(String text, Consumer<String> replacer, String newValue) {
+        if (isNullOrEmpty(text)) {
+            replacer.accept(newValue);
+        }
+    }
+
+    public static boolean isNullOrEmpty(String string) {
+        return string == null || string.trim().isEmpty();
+    }
+
+    public static boolean isNullOrEmptyList(List<String> list) {
+        return list == null || list.isEmpty();
+    }
+
+    /**
+     * Convert from Yaml to Xacml blacklist.
+     *
+     * @param yamlFile the Yaml file
+     * @param xacmlTemplate the Xacml template
+     * @param xacmlPolicyOutput the Xacml output
+     */
+    public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) {
+        ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile);
+        GuardPolicy guardPolicy = yamlGuardObject.getGuards().get(0);
+        logger.debug("actor: {}", guardPolicy.getMatch_parameters().getActor());
+        logger.debug("recipe: {}", guardPolicy.getMatch_parameters().getRecipe());
+        Constraint constraint = guardPolicy.getLimit_constraints().get(0);
+        logger.debug("freq_limit_per_target: {}", constraint.getFreq_limit_per_target());
+        logger.debug("time_window: {}", constraint.getTime_window());
+        logger.debug("active_time_range: {}", constraint.getActive_time_range());
+
+        Path xacmlTemplatePath = Paths.get(xacmlTemplate);
         String xacmlTemplateContent;
-               
+
         try {
-                       xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
-                       
-               String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent,
-                               yamlGuardObject.guards.getFirst().match_parameters.controlLoopName,
-                               yamlGuardObject.guards.getFirst().match_parameters.actor,
-                               yamlGuardObject.guards.getFirst().match_parameters.recipe,
-                               yamlGuardObject.guards.getFirst().limit_constraints.getFirst().blacklist,
-                               yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range.get("start"),
-                               yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range.get("end")
-                               );
-               
-       
-               Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
-        
-               } catch (IOException e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
-               }
-               
-       }
-       
-       public static String    generateXacmlGuardBlacklist(String xacmlFileContent, 
-                       String clname,
-                       String actor, 
-                       String recipe, 
-                       List<String> blacklist,
-                       String guardActiveStart, 
-                       String guardActiveEnd) {
-
-               
-               Pattern p = Pattern.compile("\\$\\{clname\\}");
-               Matcher m = p.matcher(xacmlFileContent);
-               if(isNullOrEmpty(clname)) clname = ".*";
-               xacmlFileContent = m.replaceAll(clname);
-               
-               p = Pattern.compile("\\$\\{actor\\}");
-               m = p.matcher(xacmlFileContent);
-               if(isNullOrEmpty(actor)) actor = ".*";
-               xacmlFileContent = m.replaceAll(actor);
-
-               p = Pattern.compile("\\$\\{recipe\\}");
-               m = p.matcher(xacmlFileContent);
-               if(isNullOrEmpty(recipe)) recipe = ".*";
-               xacmlFileContent = m.replaceAll(recipe);
-               
-               p = Pattern.compile("\\$\\{guardActiveStart\\}");
-               m = p.matcher(xacmlFileContent);
-               xacmlFileContent = m.replaceAll(guardActiveStart);
-
-               p = Pattern.compile("\\$\\{guardActiveEnd\\}");
-               m = p.matcher(xacmlFileContent);
-               xacmlFileContent = m.replaceAll(guardActiveEnd);
-               System.out.println(xacmlFileContent);
-               
-               for(String target : blacklist){
-                       p = Pattern.compile("\\$\\{blackListElement\\}");
-                       m = p.matcher(xacmlFileContent);
-                       xacmlFileContent = m.replaceAll("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" 
-                                                                                       + target
-                                                                                       + "</AttributeValue>"
-                                                                                       + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}");
-               }
-               
-               p = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n");
-               m = p.matcher(xacmlFileContent);
-               xacmlFileContent = m.replaceAll("");
-               
-               
-               return xacmlFileContent;
-       }
-       
-       
+            xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
+            String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent,
+                    guardPolicy.getMatch_parameters(), constraint);
+
+            logger.debug("{}", xacmlPolicyContent);
+
+            Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
+
+        } catch (IOException e) {
+            logger.error("fromYamlToXacmlBlacklist threw: ", e);
+        }
+    }
+
+    private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters,
+            Constraint constraint) {
+
+        String result = doCommonReplacements(xacmlTemplateContent, matchParameters, constraint);
+
+        for (String target : constraint.getBlacklist()) {
+            result = result.replace("${blackListElement}",
+                            "<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + target
+                                            + "</AttributeValue>" + "\n\t\t\t\t\t\t\\${blackListElement}\n");
+        }
+
+        result = result.replace("\t\t\t\t\t\t\\${blackListElement}\n", "");
+
+        return result;
+    }
 }