Consolidate common translatable code some sonar 31/97431/4
authorPamela Dragosh <pdragosh@research.att.com>
Tue, 22 Oct 2019 17:06:56 +0000 (13:06 -0400)
committerPamela Dragosh <pdragosh@research.att.com>
Wed, 23 Oct 2019 13:19:24 +0000 (09:19 -0400)
There is duplicate code for some common translation of policy
decision responses and for scanning obligations.

Removed some TODO items (left others because I want to look
at them more closely).

Stored System.lineSeparator into a static var so that I can
remove some unnecessary ifs. There's still one left that I
am not worried about.

Gson as a static variable.

Issue-ID: POLICY-2066
Change-Id: I9c8162d5ad1c5f884be347dd94631fa74ca76f85
Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
14 files changed:
applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java
applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java [new file with mode: 0644]
applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslator.java
applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java
applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java
applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java
applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java
applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslator.java
applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/LegacyGuardTranslator.java
applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationTest.java
applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java
applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java
applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java
main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java

index 6f2a9f0..0ca7198 100644 (file)
@@ -54,6 +54,7 @@ public class XacmlPolicyUtils {
     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPolicyUtils.class);
 
     public static final String XACML_PROPERTY_FILE = "xacml.properties";
+    public static final String LINE_SEPARATOR = System.lineSeparator();
 
     private static final String DOT_FILE_SUFFIX = ".file";
     private static final String NOT_FOUND_MESSAGE = "NOT FOUND";
@@ -375,7 +376,7 @@ public class XacmlPolicyUtils {
             Properties properties = new Properties();
             properties.load(is);
             if (LOGGER.isInfoEnabled()) {
-                LOGGER.info("Loaded xacml properties {} {}", System.lineSeparator(), properties);
+                LOGGER.info("Loaded xacml properties {} {}", XacmlPolicyUtils.LINE_SEPARATOR, properties);
                 for (Entry<Object, Object> entrySet : properties.entrySet()) {
                     LOGGER.info("{} -> {}", entrySet.getKey(), entrySet.getValue());
                 }
@@ -390,9 +391,7 @@ public class XacmlPolicyUtils {
      * @throws IOException If unable to store the file.
      */
     public static void storeXacmlProperties(Properties properties, Path propertyPath) throws IOException {
-        if (LOGGER.isInfoEnabled()) {
-            LOGGER.info("Storing xacml properties {} {} {}", properties, System.lineSeparator(), propertyPath);
-        }
+        LOGGER.info("Storing xacml properties {} {} {}", properties, XacmlPolicyUtils.LINE_SEPARATOR, propertyPath);
         try (OutputStream os = Files.newOutputStream(propertyPath)) {
             String strComments = "#";
             properties.store(os, strComments);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java
new file mode 100644 (file)
index 0000000..e3d8757
--- /dev/null
@@ -0,0 +1,201 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pdp.xacml.application.common.std;
+
+import com.att.research.xacml.api.AttributeAssignment;
+import com.att.research.xacml.api.Decision;
+import com.att.research.xacml.api.Obligation;
+import com.att.research.xacml.api.Request;
+import com.att.research.xacml.api.Response;
+import com.att.research.xacml.api.Result;
+import com.google.gson.Gson;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import org.onap.policy.models.decisions.concepts.DecisionRequest;
+import org.onap.policy.models.decisions.concepts.DecisionResponse;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
+import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
+import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
+import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
+import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class StdBaseTranslator implements ToscaPolicyTranslator {
+    private static final Logger LOGGER = LoggerFactory.getLogger(StdBaseTranslator.class);
+    private static Gson gson = new Gson();
+
+    public static final String POLICY_ID = "policy-id";
+
+    @Override
+    public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
+        throw new ToscaPolicyConversionException("Please override converPolicy");
+    }
+
+    @Override
+    public Request convertRequest(DecisionRequest request) {
+        return null;
+    }
+
+    @Override
+    public DecisionResponse convertResponse(Response xacmlResponse) {
+        LOGGER.info("Converting Response {}", xacmlResponse);
+        DecisionResponse decisionResponse = new DecisionResponse();
+        //
+        // Setup policies
+        //
+        decisionResponse.setPolicies(new HashMap<>());
+        //
+        // Iterate through all the results
+        //
+        for (Result xacmlResult : xacmlResponse.getResults()) {
+            //
+            // Check the result
+            //
+            if (xacmlResult.getDecision() == Decision.PERMIT) {
+                //
+                // Go through obligations
+                //
+                scanObligations(xacmlResult.getObligations(), decisionResponse);
+            } else if (xacmlResult.getDecision() == Decision.DENY
+                    || xacmlResult.getDecision() == Decision.INDETERMINATE) {
+                //
+                // TODO we have to return an ErrorResponse object instead
+                //
+                decisionResponse.setStatus("A better error message");
+            }
+        }
+
+        return decisionResponse;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
+        for (Obligation obligation : obligations) {
+            LOGGER.info("Obligation: {}", obligation);
+            for (AttributeAssignment assignment : obligation.getAttributeAssignments()) {
+                LOGGER.info("Attribute Assignment: {}", assignment);
+                //
+                // We care about the content attribute
+                //
+                if (ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS
+                        .equals(assignment.getAttributeId())) {
+                    //
+                    // The contents are in Json form
+                    //
+                    Object stringContents = assignment.getAttributeValue().getValue();
+                    LOGGER.info("DCAE contents: {}{}", XacmlPolicyUtils.LINE_SEPARATOR, stringContents);
+                    //
+                    // Let's parse it into a map using Gson
+                    //
+                    Map<String, Object> result;
+                    result = gson.fromJson(stringContents.toString(), Map.class);
+                    //
+                    // Find the metadata section
+                    //
+                    Map<String, Object> metadata = (Map<String, Object>) result.get("metadata");
+                    if (metadata != null) {
+                        decisionResponse.getPolicies().put(metadata.get(POLICY_ID).toString(), result);
+                    } else {
+                        LOGGER.error("Missing metadata section in policy contained in obligation.");
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
+     *
+     * @param policy Policy Object to store the metadata
+     * @param map The Metadata TOSCA Map
+     * @return Same Policy Object
+     * @throws ToscaPolicyConversionException If there is something missing from the metadata
+     */
+    protected PolicyType fillMetadataSection(PolicyType policy,
+            Map<String, String> map) throws ToscaPolicyConversionException {
+        //
+        // Ensure the policy-id exists - we don't use it here. It
+        // is saved in the TOSCA Policy Name field.
+        //
+        if (! map.containsKey(POLICY_ID)) {
+            throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-id");
+        }
+        //
+        // Ensure the policy-version exists
+        //
+        if (! map.containsKey("policy-version")) {
+            throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-version");
+        }
+        //
+        // Add in the Policy Version
+        //
+        policy.setVersion(map.get("policy-version"));
+        return policy;
+    }
+
+    protected RuleType addObligation(RuleType rule, String jsonPolicy) {
+        //
+        // Convert the YAML Policy to JSON Object
+        //
+        LOGGER.info("JSON Optimization Policy {}{}", XacmlPolicyUtils.LINE_SEPARATOR, jsonPolicy);
+        //
+        // Create an AttributeValue for it
+        //
+        AttributeValueType value = new AttributeValueType();
+        value.setDataType(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_DATATYPE.stringValue());
+        value.getContent().add(jsonPolicy);
+        //
+        // Create our AttributeAssignmentExpression where we will
+        // store the contents of the policy in JSON format.
+        //
+        AttributeAssignmentExpressionType expressionType = new AttributeAssignmentExpressionType();
+        expressionType.setAttributeId(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS.stringValue());
+        ObjectFactory factory = new ObjectFactory();
+        expressionType.setExpression(factory.createAttributeValue(value));
+        //
+        // Create an ObligationExpression for it
+        //
+        ObligationExpressionType obligation = new ObligationExpressionType();
+        obligation.setFulfillOn(EffectType.PERMIT);
+        obligation.setObligationId(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue());
+        obligation.getAttributeAssignmentExpression().add(expressionType);
+        //
+        // Now we can add it into the rule
+        //
+        ObligationExpressionsType obligations = new ObligationExpressionsType();
+        obligations.getObligationExpression().add(obligation);
+        rule.setObligationExpressions(obligations);
+        return rule;
+    }
+
+}
index 12337d2..be0a507 100644 (file)
 
 package org.onap.policy.pdp.xacml.application.common.std;
 
-import com.att.research.xacml.api.AttributeAssignment;
 import com.att.research.xacml.api.DataTypeException;
-import com.att.research.xacml.api.Decision;
-import com.att.research.xacml.api.Obligation;
 import com.att.research.xacml.api.Request;
-import com.att.research.xacml.api.Response;
-import com.att.research.xacml.api.Result;
 import com.att.research.xacml.api.XACML3;
 import com.att.research.xacml.std.annotations.RequestParser;
-import com.google.gson.Gson;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.models.decisions.concepts.DecisionRequest;
-import org.onap.policy.models.decisions.concepts.DecisionResponse;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class StdCombinedPolicyResultsTranslator implements ToscaPolicyTranslator {
+public class StdCombinedPolicyResultsTranslator extends StdBaseTranslator {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(StdCombinedPolicyResultsTranslator.class);
-    private static final String POLICY_ID = "policy-id";
 
     public StdCombinedPolicyResultsTranslator() {
         super();
@@ -139,105 +120,6 @@ public class StdCombinedPolicyResultsTranslator implements ToscaPolicyTranslator
         return null;
     }
 
-    @Override
-    public DecisionResponse convertResponse(Response xacmlResponse) {
-        LOGGER.info("Converting Response {}", xacmlResponse);
-        DecisionResponse decisionResponse = new DecisionResponse();
-        //
-        // Setup policies
-        //
-        decisionResponse.setPolicies(new HashMap<>());
-        //
-        // Iterate through all the results
-        //
-        for (Result xacmlResult : xacmlResponse.getResults()) {
-            //
-            // Check the result
-            //
-            if (xacmlResult.getDecision() == Decision.PERMIT) {
-                //
-                // Go through obligations
-                //
-                scanObligations(xacmlResult.getObligations(), decisionResponse);
-            }
-            if (xacmlResult.getDecision() == Decision.DENY
-                    || xacmlResult.getDecision() == Decision.INDETERMINATE) {
-                //
-                // TODO we have to return an ErrorResponse object instead
-                //
-                decisionResponse.setStatus("A better error message");
-            }
-        }
-
-        return decisionResponse;
-    }
-
-    protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
-        for (Obligation obligation : obligations) {
-            LOGGER.info("Obligation: {}", obligation);
-            for (AttributeAssignment assignment : obligation.getAttributeAssignments()) {
-                LOGGER.info("Attribute Assignment: {}", assignment);
-                //
-                // We care about the content attribute
-                //
-                if (ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS
-                        .equals(assignment.getAttributeId())) {
-                    //
-                    // The contents are in Json form
-                    //
-                    Object stringContents = assignment.getAttributeValue().getValue();
-                    if (LOGGER.isInfoEnabled()) {
-                        LOGGER.info("DCAE contents: {}{}", System.lineSeparator(), stringContents);
-                    }
-                    //
-                    // Let's parse it into a map using Gson
-                    //
-                    Gson gson = new Gson();
-                    @SuppressWarnings("unchecked")
-                    Map<String, Object> result = gson.fromJson(stringContents.toString() ,Map.class);
-                    //
-                    // Find the metadata section
-                    //
-                    @SuppressWarnings("unchecked")
-                    Map<String, Object> metadata = (Map<String, Object>) result.get("metadata");
-                    if (metadata != null) {
-                        decisionResponse.getPolicies().put(metadata.get(POLICY_ID).toString(), result);
-                    } else {
-                        LOGGER.error("Missing metadata section in policy contained in obligation.");
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
-     *
-     * @param policy Policy Object to store the metadata
-     * @param map The Metadata TOSCA Map
-     * @return Same Policy Object
-     * @throws ToscaPolicyConversionException If there is something missing from the metadata
-     */
-    protected PolicyType fillMetadataSection(PolicyType policy,
-            Map<String, String> map) throws ToscaPolicyConversionException {
-        if (! map.containsKey(POLICY_ID)) {
-            throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-id");
-        } else {
-            //
-            // Do nothing here - the XACML PolicyId is used from TOSCA Policy Name field
-            //
-        }
-        if (! map.containsKey("policy-version")) {
-            throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-version");
-        } else {
-            //
-            // Add in the Policy Version
-            //
-            policy.setVersion(map.get("policy-version"));
-        }
-        return policy;
-    }
-
     protected TargetType generateTargetType(String policyId, String policyType, String policyTypeVersion) {
         //
         // Create all the match's that are possible
@@ -293,41 +175,4 @@ public class StdCombinedPolicyResultsTranslator implements ToscaPolicyTranslator
         return target;
     }
 
-    protected RuleType addObligation(RuleType rule, String jsonPolicy) {
-        //
-        // Convert the YAML Policy to JSON Object
-        //
-        if (LOGGER.isInfoEnabled()) {
-            LOGGER.info("JSON DCAE Policy {}{}", System.lineSeparator(), jsonPolicy);
-        }
-        //
-        // Create an AttributeValue for it
-        //
-        AttributeValueType value = new AttributeValueType();
-        value.setDataType(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_DATATYPE.stringValue());
-        value.getContent().add(jsonPolicy);
-        //
-        // Create our AttributeAssignmentExpression where we will
-        // store the contents of the policy in JSON format.
-        //
-        AttributeAssignmentExpressionType expressionType = new AttributeAssignmentExpressionType();
-        expressionType.setAttributeId(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS.stringValue());
-        ObjectFactory factory = new ObjectFactory();
-        expressionType.setExpression(factory.createAttributeValue(value));
-        //
-        // Create an ObligationExpression for it
-        //
-        ObligationExpressionType obligation = new ObligationExpressionType();
-        obligation.setFulfillOn(EffectType.PERMIT);
-        obligation.setObligationId(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue());
-        obligation.getAttributeAssignmentExpression().add(expressionType);
-        //
-        // Now we can add it into the rule
-        //
-        ObligationExpressionsType obligations = new ObligationExpressionsType();
-        obligations.getObligationExpression().add(obligation);
-        rule.setObligationExpressions(obligations);
-        return rule;
-    }
-
 }
index 2d831f6..5908f53 100644 (file)
 
 package org.onap.policy.pdp.xacml.application.common.std;
 
-import com.att.research.xacml.api.AttributeAssignment;
-import com.att.research.xacml.api.Decision;
 import com.att.research.xacml.api.Identifier;
-import com.att.research.xacml.api.Obligation;
 import com.att.research.xacml.api.Request;
-import com.att.research.xacml.api.Response;
-import com.att.research.xacml.api.Result;
 import com.att.research.xacml.api.XACML3;
 import com.att.research.xacml.std.IdentifierImpl;
 import com.att.research.xacml.util.XACMLPolicyWriter;
-import com.google.gson.Gson;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
@@ -49,13 +43,8 @@ import java.util.Map;
 import java.util.Map.Entry;
 import lombok.Setter;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
@@ -64,7 +53,6 @@ import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.common.utils.coder.StandardYamlCoder;
 import org.onap.policy.models.decisions.concepts.DecisionRequest;
-import org.onap.policy.models.decisions.concepts.DecisionResponse;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
@@ -75,7 +63,6 @@ import org.onap.policy.pdp.xacml.application.common.PolicyApiCaller;
 import org.onap.policy.pdp.xacml.application.common.PolicyApiException;
 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
 import org.slf4j.Logger;
@@ -88,10 +75,9 @@ import org.slf4j.LoggerFactory;
  * @author pameladragosh
  *
  */
-public class StdMatchableTranslator implements ToscaPolicyTranslator {
+public class StdMatchableTranslator  extends StdBaseTranslator {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(StdMatchableTranslator.class);
-    private static final String POLICY_ID = "policy-id";
     private static final StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
 
     private final Map<ToscaPolicyTypeIdentifier, ToscaPolicyType> matchablePolicyTypes = new HashMap<>();
@@ -118,82 +104,6 @@ public class StdMatchableTranslator implements ToscaPolicyTranslator {
         return null;
     }
 
-    @Override
-    public DecisionResponse convertResponse(Response xacmlResponse) {
-        LOGGER.info("Converting Response {}", xacmlResponse);
-        DecisionResponse decisionResponse = new DecisionResponse();
-        //
-        // Setup policies
-        //
-        decisionResponse.setPolicies(new HashMap<>());
-        //
-        // Iterate through all the results
-        //
-        for (Result xacmlResult : xacmlResponse.getResults()) {
-            //
-            // Check the result
-            //
-            if (xacmlResult.getDecision() == Decision.PERMIT) {
-                //
-                // Go through obligations
-                //
-                scanObligations(xacmlResult.getObligations(), decisionResponse);
-            }
-            if (xacmlResult.getDecision() == Decision.DENY
-                    || xacmlResult.getDecision() == Decision.INDETERMINATE) {
-                //
-                // TODO we have to return an ErrorResponse object instead
-                //
-                decisionResponse.setStatus("A better error message");
-            }
-        }
-
-        return decisionResponse;
-    }
-
-    protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
-        for (Obligation obligation : obligations) {
-            LOGGER.info("Obligation: {}", obligation);
-            for (AttributeAssignment assignment : obligation.getAttributeAssignments()) {
-                LOGGER.info("Attribute Assignment: {}", assignment);
-                //
-                // We care about the content attribute
-                //
-                if (! ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS
-                        .equals(assignment.getAttributeId())) {
-                    //
-                    // If its not there, move on
-                    //
-                    continue;
-                }
-                //
-                // The contents are in Json form
-                //
-                Object stringContents = assignment.getAttributeValue().getValue();
-                if (LOGGER.isInfoEnabled()) {
-                    LOGGER.info("Policy contents: {}{}", System.lineSeparator(), stringContents);
-                }
-                //
-                // Let's parse it into a map using Gson
-                //
-                Gson gson = new Gson();
-                @SuppressWarnings("unchecked")
-                Map<String, Object> result = gson.fromJson(stringContents.toString() ,Map.class);
-                //
-                // Find the metadata section
-                //
-                @SuppressWarnings("unchecked")
-                Map<String, Object> metadata = (Map<String, Object>) result.get("metadata");
-                if (metadata != null) {
-                    decisionResponse.getPolicies().put(metadata.get(POLICY_ID).toString(), result);
-                } else {
-                    LOGGER.error("Missing metadata section in policy contained in obligation.");
-                }
-            }
-        }
-
-    }
-
     @Override
     public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
         //
@@ -270,34 +180,6 @@ public class StdMatchableTranslator implements ToscaPolicyTranslator {
         return newPolicyType;
     }
 
-    /**
-     * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
-     *
-     * @param policy Policy Object to store the metadata
-     * @param map The Metadata TOSCA Map
-     * @return Same Policy Object
-     * @throws ToscaPolicyConversionException If there is something missing from the metadata
-     */
-    protected PolicyType fillMetadataSection(PolicyType policy,
-            Map<String, String> map) throws ToscaPolicyConversionException {
-        if (! map.containsKey(POLICY_ID)) {
-            throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-id");
-        } else {
-            //
-            // Do nothing here - the XACML PolicyId is used from TOSCA Policy Name field
-            //
-        }
-        if (! map.containsKey("policy-version")) {
-            throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-version");
-        } else {
-            //
-            // Add in the Policy Version
-            //
-            policy.setVersion(map.get("policy-version"));
-        }
-        return policy;
-    }
-
     /**
      * For generating target type, we are scan for matchable properties
      * and use those to build the policy.
@@ -368,7 +250,7 @@ public class StdMatchableTranslator implements ToscaPolicyTranslator {
             //
             // See if we are another datatype
             //
-            // TODO We should add datetime support. But to do that we need
+            // We should add datetime support. But to do that we need
             // probably more metadata to describe how that would be translated.
             //
             if (matchable instanceof Integer) {
@@ -398,44 +280,6 @@ public class StdMatchableTranslator implements ToscaPolicyTranslator {
         return anyOf;
     }
 
-    protected RuleType addObligation(RuleType rule, String jsonPolicy) {
-        //
-        // Convert the YAML Policy to JSON Object
-        //
-        if (LOGGER.isInfoEnabled()) {
-            LOGGER.info("JSON Optimization Policy {}{}", System.lineSeparator(), jsonPolicy);
-        }
-        //
-        // Create an AttributeValue for it
-        //
-        AttributeValueType value = new AttributeValueType();
-        value.setDataType(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_DATATYPE.stringValue());
-        value.getContent().add(jsonPolicy);
-        //
-        // Create our AttributeAssignmentExpression where we will
-        // store the contents of the policy in JSON format.
-        //
-        AttributeAssignmentExpressionType expressionType = new AttributeAssignmentExpressionType();
-        expressionType.setAttributeId(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS.stringValue());
-        ObjectFactory factory = new ObjectFactory();
-        expressionType.setExpression(factory.createAttributeValue(value));
-        //
-        // Create an ObligationExpression for it
-        //
-        ObligationExpressionType obligation = new ObligationExpressionType();
-        obligation.setFulfillOn(EffectType.PERMIT);
-        obligation.setObligationId(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue());
-        obligation.getAttributeAssignmentExpression().add(expressionType);
-        //
-        // Now we can add it into the rule
-        //
-        ObligationExpressionsType obligations = new ObligationExpressionsType();
-        obligations.getObligationExpression().add(obligation);
-        rule.setObligationExpressions(obligations);
-        return rule;
-    }
-
-
     /**
      * Get Policy Type definitions. This could be previously loaded, or could be
      * stored in application path, or may need to be pulled from the API.
index 5f639c5..12135f4 100644 (file)
@@ -30,6 +30,7 @@ import com.att.research.xacml.api.pdp.PDPException;
 import com.att.research.xacml.util.FactoryException;
 import com.att.research.xacml.util.XACMLPolicyWriter;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.Collections;
@@ -139,7 +140,8 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
             //
             XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
             if (LOGGER.isInfoEnabled()) {
-                LOGGER.info("Xacml Policy is {}{}", System.lineSeparator(), new String(Files.readAllBytes(refPath)));
+                LOGGER.info("Xacml Policy is {}{}", XacmlPolicyUtils.LINE_SEPARATOR,
+                    new String(Files.readAllBytes(refPath), StandardCharsets.UTF_8));
             }
             //
             // Add root policy to properties object
index 318d9f9..1e13d52 100644 (file)
@@ -222,7 +222,7 @@ public class XacmlPolicyUtilsTest {
             //
             try (OutputStream os = new ByteArrayOutputStream()) {
                 XACMLPolicyWriter.writePolicyFile(os, rootPolicy);
-                LOGGER.debug("New Root Policy:{}{}", System.lineSeparator(), os.toString());
+                LOGGER.debug("New Root Policy:{}{}", XacmlPolicyUtils.LINE_SEPARATOR, os);
             }
             //
             // Just update root and PolicySet
@@ -230,7 +230,7 @@ public class XacmlPolicyUtilsTest {
             XacmlPolicyUtils.addPolicySetsToXacmlRootPolicy(rootPolicy, policySet5);
             try (OutputStream os = new ByteArrayOutputStream()) {
                 XACMLPolicyWriter.writePolicyFile(os, rootPolicy);
-                LOGGER.debug("New Root Policy:{}{}", System.lineSeparator(), os.toString());
+                LOGGER.debug("New Root Policy:{}{}", XacmlPolicyUtils.LINE_SEPARATOR, os);
             }
         }).doesNotThrowAnyException();
     }
index 3323040..07317c0 100644 (file)
@@ -57,6 +57,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
+import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -131,7 +132,7 @@ public class StdMatchableTranslatorTest {
         assertEquals(1, completedJtst.getPolicyTypes().size());
         testPolicyType = completedJtst.getPolicyTypes().get("onap.policies.Test");
         assertNotNull(testPolicyType);
-        logger.info("Test Policy Type {}{}", System.lineSeparator(), testPolicyType);
+        logger.info("Test Policy Type {}{}", XacmlPolicyUtils.LINE_SEPARATOR, testPolicyType);
     }
 
     @AfterClass
@@ -173,7 +174,7 @@ public class StdMatchableTranslatorTest {
             for (ToscaPolicy policy : policies.values()) {
                 PolicyType translatedPolicy = translator.convertPolicy(policy);
                 assertNotNull(translatedPolicy);
-                logger.info("Translated policy {} {}", System.lineSeparator(), translatedPolicy);
+                logger.info("Translated policy {} {}", XacmlPolicyUtils.LINE_SEPARATOR, translatedPolicy);
             }
         }
     }
index 92e0301..eb793f6 100644 (file)
@@ -50,6 +50,7 @@ import org.onap.policy.models.decisions.concepts.DecisionResponse;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
+import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -153,7 +154,7 @@ public class CoordinationGuardTranslator implements ToscaPolicyTranslator {
             return stream.map(s -> s.replaceAll("UNIQUE_ID", uniqueId))
                 .map(s -> s.replaceAll("CONTROL_LOOP_ONE", cLOne))
                 .map(s -> s.replaceAll("CONTROL_LOOP_TWO", cLTwo))
-                .collect(Collectors.joining(System.lineSeparator()));
+                .collect(Collectors.joining(XacmlPolicyUtils.LINE_SEPARATOR));
         } catch (IOException e) {
             throw new
                 ToscaPolicyConversionException("Error while generating XACML policy for coordination directive", e);
index 3ccbd9c..0cb06ea 100644 (file)
@@ -342,10 +342,6 @@ public class LegacyGuardTranslator implements ToscaPolicyTranslator {
         //
         permit.setCondition(condition);
         //
-        // TODO Add the advice - Is the request id needed to be returned?
-        //
-        // permit . setAdviceExpressions (adviceExpressions)
-        //
         // Done
         //
         return permit;
@@ -400,10 +396,6 @@ public class LegacyGuardTranslator implements ToscaPolicyTranslator {
         //
         permit.setCondition(createCondition(timeRange, minApply, maxApply));
         //
-        // TODO Add the advice - Is the request id needed to be returned?
-        //
-        // permit . setAdviceExpressions (adviceExpressions)
-        //
         // Done
         //
         return permit;
index efa0bdc..c75156d 100644 (file)
@@ -106,7 +106,7 @@ public class CoordinationTest {
         //
         // Find the guard service application and save for use in all the tests
         //
-        StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
+        StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
         while (iterator.hasNext()) {
             XacmlApplicationServiceProvider application = iterator.next();
@@ -123,7 +123,7 @@ public class CoordinationTest {
             strDump.append(application.applicationName());
             strDump.append(" supports ");
             strDump.append(application.supportedPolicyTypes());
-            strDump.append(System.lineSeparator());
+            strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
         }
         LOGGER.info("{}", strDump);
         //
index 7435fb9..9c3ae5b 100644 (file)
@@ -104,7 +104,7 @@ public class GuardPdpApplicationTest {
         //
         // Find the guard service application and save for use in all the tests
         //
-        StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
+        StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
         while (iterator.hasNext()) {
             XacmlApplicationServiceProvider application = iterator.next();
@@ -121,7 +121,7 @@ public class GuardPdpApplicationTest {
             strDump.append(application.applicationName());
             strDump.append(" supports ");
             strDump.append(application.supportedPolicyTypes());
-            strDump.append(System.lineSeparator());
+            strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
         }
         LOGGER.info("{}", strDump);
         //
index 1cba496..fcb99f3 100644 (file)
@@ -103,7 +103,7 @@ public class MonitoringPdpApplicationTest {
         //
         // Look for our class instance and save it
         //
-        StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
+        StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
         while (iterator.hasNext()) {
             XacmlApplicationServiceProvider application = iterator.next();
@@ -120,7 +120,7 @@ public class MonitoringPdpApplicationTest {
             strDump.append(application.applicationName());
             strDump.append(" supports ");
             strDump.append(application.supportedPolicyTypes());
-            strDump.append(System.lineSeparator());
+            strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
         }
         LOGGER.debug("{}", strDump);
         //
index 11a7a92..b84ec07 100644 (file)
@@ -125,7 +125,7 @@ public class OptimizationPdpApplicationTest {
         // the optimization service. Save it for use throughout
         // all the Junit tests.
         //
-        StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
+        StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
         while (iterator.hasNext()) {
             XacmlApplicationServiceProvider application = iterator.next();
@@ -142,7 +142,7 @@ public class OptimizationPdpApplicationTest {
             strDump.append(application.applicationName());
             strDump.append(" supports ");
             strDump.append(application.supportedPolicyTypes());
-            strDump.append(System.lineSeparator());
+            strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
         }
         LOGGER.debug("{}", strDump);
         assertThat(service).isNotNull();
index 4244e56..37a669d 100644 (file)
@@ -268,7 +268,7 @@ public class TestAbbreviateDecisionResults {
         //
         // Look for our class instance and save it
         //
-        StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
+        StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
         for (XacmlApplicationServiceProvider application : applicationLoader) {
             //
             // Is it our service?
@@ -283,7 +283,7 @@ public class TestAbbreviateDecisionResults {
             strDump.append(application.applicationName());
             strDump.append(" supports ");
             strDump.append(application.supportedPolicyTypes());
-            strDump.append(System.lineSeparator());
+            strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
         }
         LOGGER.debug("{}", strDump);
         //