Fix more sonar issues in drools-applications 88/98188/2
authorJim Hahn <jrh3@att.com>
Fri, 8 Nov 2019 13:54:40 +0000 (08:54 -0500)
committerJim Hahn <jrh3@att.com>
Fri, 8 Nov 2019 15:19:53 +0000 (10:19 -0500)
Addressed the following sonar issues:
- unused imports
- unused method parameters
- superfluous "throws" declaration
- fields within a serializable class must also be serializable; this
  was/will be fixed with a change to AaiCqResponse in policy-models
- use logger instead of System.out; turns out that the code that used
  System.out is no longer needed.  In fact, deleted several classes
  that are no longer needed: ControlLoopLogger and ControlLoopPublisher
- cyclomatic complexity and switch/case statements too big; used
  eclipse to extract chunks of code into separate methods
- duplicate code
  Note: extracted common code and used lambdas to eliminate duplicate
  code in PolicyGuardYamlToXacml.  However, a better approach would be
  to use object-oriented programming, using mini/nested objects to do
  the generation.  The lambdas would then become abstract methods.
  Nevertheless, that would entail significantly more re-write of this
  class than desired at this time

Issue-ID: POLICY-2225
Change-Id: Ie503ffd7accbad3e410af602d32b29c0095c3a33
Signed-off-by: Jim Hahn <jrh3@att.com>
13 files changed:
controlloop/common/controller-usecases/src/main/resources/usecases.drl
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java [deleted file]
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java [deleted file]
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java [deleted file]
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java [deleted file]
controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java [deleted file]
controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java [deleted file]
controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java
controlloop/common/feature-controlloop-utils/src/main/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeature.java
controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java
controlloop/templates/archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl

index e0b7bb2..54295e9 100644 (file)
@@ -28,7 +28,6 @@ import org.onap.policy.controlloop.VirtualControlLoopNotification;
 import org.onap.policy.controlloop.ControlLoopEventStatus;
 import org.onap.policy.controlloop.ControlLoopException;
 import org.onap.policy.controlloop.ControlLoopNotificationType;
-import org.onap.policy.controlloop.ControlLoopLogger;
 import org.onap.policy.controlloop.ControlLoopResponse;
 import org.onap.policy.controlloop.policy.PolicyResult;
 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java
deleted file mode 100644 (file)
index 4bf5007..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * controlloop
- * ================================================================================
- * Copyright (C) 2017-2018 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.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.controlloop;
-
-import java.lang.reflect.Constructor;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public interface ControlLoopLogger {
-
-    public void info(String... parameters);
-
-    public void metrics(String... msgs);
-
-    public void metrics(Object obj);
-
-    public static class Factory {
-        private static final Logger logger = LoggerFactory.getLogger(Factory.class);
-
-        /**
-         * Construct an instance.
-         * 
-         * @param className name of the class
-         * @return the instance
-         * @throws ControlLoopException if an error occurs
-         */
-        public ControlLoopLogger buildLogger(String className) throws ControlLoopException {
-            try {
-                Constructor<?> constr = Class.forName(className).getConstructor();
-                return (ControlLoopLogger) constr.newInstance();
-            } catch (Exception e) {
-                logger.error("buildLogger threw: ", e);
-                throw new ControlLoopException("Cannot load class " + className + " as a control loop logger");
-            }
-        }
-    }
-}
diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java
deleted file mode 100644 (file)
index 086e117..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * controlloop
- * ================================================================================
- * Copyright (C) 2017-2018 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.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.controlloop;
-
-import java.lang.reflect.Constructor;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@FunctionalInterface
-public interface ControlLoopPublisher {
-
-    public void publish(Object object);
-
-    public static class Factory {
-        private static final Logger logger = LoggerFactory.getLogger(Factory.class);
-
-        /**
-         * Construct an instance.
-         * 
-         * @param className name of the class
-         * @return the instance
-         * @throws ControlLoopException if an error occurs
-         */
-        public ControlLoopPublisher buildLogger(String className) throws ControlLoopException {
-            try {
-                Constructor<?> constr = Class.forName(className).getConstructor();
-                return (ControlLoopPublisher) constr.newInstance();
-            } catch (Exception e) {
-                logger.error("ControlLoopPublisher.buildLogger threw: ", e);
-                throw new ControlLoopException("Cannot load class " + className + " as a control loop publisher");
-            }
-        }
-    }
-}
index c01bec4..8b06a96 100644 (file)
@@ -746,22 +746,30 @@ public class ControlLoopEventManager implements Serializable {
         switch (event.getTargetType()) {
             case VM:
             case VNF:
-                if (eventAai.get(GENERIC_VNF_VNF_ID) == null && eventAai.get(VSERVER_VSERVER_NAME) == null
-                            && eventAai.get(GENERIC_VNF_VNF_NAME) == null) {
-                    throw new ControlLoopException(
-                            "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
-                }
+                validateAaiVmVnfData(eventAai);
                 return;
             case PNF:
-                if (eventAai.get(PNF_NAME) == null) {
-                    throw new ControlLoopException("AAI PNF object key pnf-name is missing");
-                }
+                validateAaiPnfData(eventAai);
                 return;
             default:
                 throw new ControlLoopException("The target type is not supported");
         }
     }
 
+    private void validateAaiVmVnfData(Map<String, String> eventAai) throws ControlLoopException {
+        if (eventAai.get(GENERIC_VNF_VNF_ID) == null && eventAai.get(VSERVER_VSERVER_NAME) == null
+                    && eventAai.get(GENERIC_VNF_VNF_NAME) == null) {
+            throw new ControlLoopException(
+                    "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
+        }
+    }
+
+    private void validateAaiPnfData(Map<String, String> eventAai) throws ControlLoopException {
+        if (eventAai.get(PNF_NAME) == null) {
+            throw new ControlLoopException("AAI PNF object key pnf-name is missing");
+        }
+    }
+
     /**
      * Query A&AI for an event.
      *
@@ -772,19 +780,7 @@ public class ControlLoopEventManager implements Serializable {
 
         Map<String, String> aai = event.getAai();
 
-        if (aai.containsKey(VSERVER_IS_CLOSED_LOOP_DISABLED) || aai.containsKey(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)
-                    || aai.containsKey(PNF_IS_IN_MAINT)) {
-
-            if (isClosedLoopDisabled(event)) {
-                throw new AaiException(
-                        "is-closed-loop-disabled is set to true on VServer or VNF or in-maint is set to true for PNF");
-            }
-
-            if (isProvStatusInactive(event)) {
-                throw new AaiException("prov-status is not ACTIVE on VServer or VNF or PNF");
-            }
-
-            // no need to query, as we already have the data
+        if (alreadyHaveData(event, aai)) {
             return;
         }
 
@@ -810,6 +806,26 @@ public class ControlLoopEventManager implements Serializable {
         }
     }
 
+    private boolean alreadyHaveData(VirtualControlLoopEvent event, Map<String, String> aai) throws AaiException {
+        if (aai.containsKey(VSERVER_IS_CLOSED_LOOP_DISABLED) || aai.containsKey(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)
+                    || aai.containsKey(PNF_IS_IN_MAINT)) {
+
+            if (isClosedLoopDisabled(event)) {
+                throw new AaiException(
+                        "is-closed-loop-disabled is set to true on VServer or VNF or in-maint is set to true for PNF");
+            }
+
+            if (isProvStatusInactive(event)) {
+                throw new AaiException("prov-status is not ACTIVE on VServer or VNF or PNF");
+            }
+
+            // no need to query, as we already have the data
+            return true;
+        }
+
+        return false;
+    }
+
     /**
      * Process a response from A&AI for a VNF.
      *
index 5702741..9353ac2 100644 (file)
@@ -136,26 +136,7 @@ public class ControlLoopOperationManager implements Serializable {
 
             this.targetEntity = getTarget(policy);
 
-            //
-            // Let's make a sanity check
-            //
-            switch (policy.getActor()) {
-                case "APPC":
-                    initAppc(onset, policy);
-                    break;
-                case "SO":
-                    break;
-                case "SDNR":
-                    break;
-                case "VFC":
-                    break;
-                case "SDNC":
-                    break;
-                case "CDS":
-                    break;
-                default:
-                    throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
-            }
+            initActor(policy);
 
         } catch (AaiException e) {
             throw new ControlLoopException(e.getMessage(), e);
@@ -163,7 +144,31 @@ public class ControlLoopOperationManager implements Serializable {
     }
 
 
-    private void initAppc(ControlLoopEvent onset, Policy policy) throws AaiException {
+    private void initActor(Policy policy) throws AaiException, ControlLoopException {
+        //
+        // Let's make a sanity check
+        //
+        switch (policy.getActor()) {
+            case "APPC":
+                initAppc(policy);
+                break;
+            case "SO":
+                break;
+            case "SDNR":
+                break;
+            case "VFC":
+                break;
+            case "SDNC":
+                break;
+            case "CDS":
+                break;
+            default:
+                throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
+        }
+    }
+
+
+    private void initAppc(Policy policy) throws AaiException {
         if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
             /*
              * The target vnf-id may not be the same as the source vnf-id specified in the yaml, the target
@@ -383,7 +388,7 @@ public class ControlLoopOperationManager implements Serializable {
     }
 
 
-    private Object startSoOperation(ControlLoopEvent onset, Operation operation) throws AaiException {
+    private Object startSoOperation(ControlLoopEvent onset, Operation operation) {
         SoActorServiceProvider soActorSp = new SoActorServiceProvider();
         if (Boolean.valueOf(PolicyEngineConstants.getManager().getEnvironmentProperty(AAI_CUSTOM_QUERY))) {
             this.operationRequest =
@@ -405,7 +410,7 @@ public class ControlLoopOperationManager implements Serializable {
     }
 
 
-    private Object startVfcOperation(ControlLoopEvent onset, Operation operation) throws AaiException {
+    private Object startVfcOperation(ControlLoopEvent onset, Operation operation) {
         if (Boolean.valueOf(PolicyEngineConstants.getManager().getEnvironmentProperty(AAI_CUSTOM_QUERY))) {
             this.operationRequest = VfcActorServiceProvider.constructRequestCq((VirtualControlLoopEvent) onset,
                     operation.clOperation, this.policy, this.aaiCqResponse);
diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java
deleted file mode 100644 (file)
index fbff87f..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * controlloop
- * ================================================================================
- * Copyright (C) 2017-2018 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.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-
-package org.onap.policy.controlloop.impl;
-
-import org.onap.policy.controlloop.ControlLoopLogger;
-
-public class ControlLoopLoggerStdOutImpl implements ControlLoopLogger {
-    @Override
-    public void info(String... parameters) {
-        StringBuilder builder = new StringBuilder();
-        for (String param : parameters) {
-            builder.append(param);
-            builder.append(" ");
-        }
-        System.out.println(builder.toString().trim());
-    }
-
-    @Override
-    public void metrics(String... msgs) {
-        this.info(msgs);
-    }
-
-    @Override
-    public void metrics(Object obj) {
-        this.info(obj.toString());
-    }
-}
diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java
deleted file mode 100644 (file)
index 0676637..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * controlloop
- * ================================================================================
- * 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.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.controlloop.impl;
-
-import org.onap.policy.controlloop.ControlLoopPublisher;
-
-public class ControlLoopPublisherJUnitImpl implements ControlLoopPublisher {
-    @Override
-    public void publish(Object object) {
-        throw new UnsupportedOperationException(
-                "publish() method is not implemented on " + this.getClass().getName());
-    }
-}
diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java
deleted file mode 100644 (file)
index 35e4d53..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * eventmanager
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.controlloop;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertNotNull;
-
-import org.junit.Test;
-import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl;
-
-public class ControlLoopLoggerTest {
-    @Test
-    public void testControlLoopLogger() throws ControlLoopException {
-        ControlLoopLogger logger =
-                new ControlLoopLogger.Factory().buildLogger(ControlLoopLoggerStdOutImpl.class.getName());
-        assertNotNull(logger);
-        logger.info("a log message", "and another", " and another");
-        logger.metrics("a metric", "and another", " and another");
-        logger.metrics(Double.valueOf(3));
-
-        assertThatThrownBy(() -> new ControlLoopLogger.Factory().buildLogger("java.lang.String"))
-                        .hasMessage("Cannot load class java.lang.String as a control loop logger");
-    }
-}
diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java
deleted file mode 100644 (file)
index 42b721e..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * eventmanager
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 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.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.controlloop;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertNotNull;
-
-import org.junit.Test;
-import org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl;
-
-public class ControlLoopPublisherTest {
-    @Test
-    public void testControlLoopPublisher() throws ControlLoopException {
-        ControlLoopPublisher publisher =
-                new ControlLoopPublisher.Factory().buildLogger(ControlLoopPublisherJUnitImpl.class.getName());
-        assertNotNull(publisher);
-
-        assertThatThrownBy(() -> publisher.publish(Double.valueOf(3)))
-            .hasMessage("publish() method is not implemented on "
-                            + "org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl");
-
-        assertThatThrownBy(() -> new ControlLoopPublisher.Factory().buildLogger("java.lang.String"))
-            .hasMessage("Cannot load class java.lang.String as a control loop publisher");
-    }
-}
index b3e2e21..2a44f6e 100644 (file)
@@ -64,7 +64,6 @@ import org.onap.policy.controlloop.ControlLoopTargetType;
 import org.onap.policy.controlloop.SupportUtil;
 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 import org.onap.policy.controlloop.VirtualControlLoopNotification;
-import org.onap.policy.controlloop.policy.ControlLoop;
 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 import org.onap.policy.controlloop.policy.Policy;
 import org.onap.policy.controlloop.policy.PolicyResult;
index 057c3f1..60ccce0 100644 (file)
@@ -48,15 +48,33 @@ public class PolicyGuardYamlToXacml {
      * @param xacmlPolicyOutput the Xacml output
      */
     public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) {
+        fromYamlToXacml(yamlFile, xacmlTemplate, xacmlPolicyOutput, PolicyGuardYamlToXacml::generateXacmlGuard,
+            constraint -> {
+                logger.debug("num: {}", constraint.getFreq_limit_per_target());
+                logger.debug("duration: {}", constraint.getTime_window());
+                logger.debug("time_in_range: {}", constraint.getActive_time_range());
+            });
+    }
+
+    /**
+     * Convert from Yaml to Xacml.
+     *
+     * @param yamlFile the Yaml file
+     * @param xacmlTemplate the Xacml template
+     * @param xacmlPolicyOutput the Xacml output
+     * @param generator function to generate the yaml from the xacml
+     * @param logConstraint function to log relevant fields of the constraint
+     */
+    public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput,
+                    Generator generator, Consumer<Constraint> logConstraint) {
+
         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());
+        logConstraint.accept(constraint);
 
         Path xacmlTemplatePath = Paths.get(xacmlTemplate);
         String xacmlTemplateContent;
@@ -64,7 +82,7 @@ public class PolicyGuardYamlToXacml {
         try {
             xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
 
-            String xacmlPolicyContent = generateXacmlGuard(xacmlTemplateContent,
+            String xacmlPolicyContent = generator.apply(xacmlTemplateContent,
                     guardPolicy.getMatch_parameters(), constraint);
 
             Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
@@ -160,30 +178,12 @@ public class PolicyGuardYamlToXacml {
      * @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,
-                    guardPolicy.getMatch_parameters(), constraint);
-
-            logger.debug("{}", xacmlPolicyContent);
-
-            Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
-
-        } catch (IOException e) {
-            logger.error("fromYamlToXacmlBlacklist threw: ", e);
-        }
+        fromYamlToXacml(yamlFile, xacmlTemplate, xacmlPolicyOutput, PolicyGuardYamlToXacml::generateXacmlGuardBlacklist,
+            constraint -> {
+                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());
+            });
     }
 
     private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters,
@@ -201,4 +201,10 @@ public class PolicyGuardYamlToXacml {
 
         return result;
     }
+
+    @FunctionalInterface
+    private static interface Generator {
+        public String apply(String xacmlTemplateContent, MatchParameters matchParameters,
+            Constraint constraint);
+    }
 }
index 40c2f18..d3c95a7 100644 (file)
@@ -28,7 +28,6 @@ import org.onap.policy.controlloop.VirtualControlLoopNotification;
 import org.onap.policy.controlloop.ControlLoopEventStatus;
 import org.onap.policy.controlloop.ControlLoopException;
 import org.onap.policy.controlloop.ControlLoopNotificationType;
-import org.onap.policy.controlloop.ControlLoopLogger;
 import org.onap.policy.controlloop.policy.PolicyResult;
 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 import org.onap.policy.controlloop.policy.Policy;