Fix sonars in xacml-pdp
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / std / StdMatchableTranslator.java
index addb0df..1d76d0e 100644 (file)
@@ -2,7 +2,8 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2021 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -22,6 +23,7 @@
 
 package org.onap.policy.pdp.xacml.application.common.std;
 
+import com.att.research.xacml.api.Advice;
 import com.att.research.xacml.api.Identifier;
 import com.att.research.xacml.api.Obligation;
 import com.att.research.xacml.api.Request;
@@ -34,10 +36,7 @@ import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
@@ -45,23 +44,23 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import lombok.Setter;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
 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.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.apache.commons.lang3.tuple.Pair;
-import org.onap.policy.common.endpoints.parameters.RestServerParameters;
+import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 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.ToscaConceptIdentifier;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
 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;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
 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.OnapObligation;
@@ -71,6 +70,9 @@ 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.ToscaPolicyTranslatorUtils;
 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
+import org.onap.policy.pdp.xacml.application.common.matchable.MatchableCallback;
+import org.onap.policy.pdp.xacml.application.common.matchable.MatchablePolicyType;
+import org.onap.policy.pdp.xacml.application.common.matchable.MatchableProperty;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -81,14 +83,16 @@ import org.slf4j.LoggerFactory;
  * @author pameladragosh
  *
  */
-public class StdMatchableTranslator  extends StdBaseTranslator {
+public class StdMatchableTranslator  extends StdBaseTranslator implements MatchableCallback {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(StdMatchableTranslator.class);
     private static final StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
 
-    private final Map<ToscaPolicyTypeIdentifier, ToscaPolicyType> matchablePolicyTypes = new HashMap<>();
+    private final Map<ToscaConceptIdentifier, ToscaServiceTemplate> matchablePolicyTypes = new HashMap<>();
+    private final Map<ToscaConceptIdentifier, MatchablePolicyType> matchableCache = new HashMap<>();
+
     @Setter
-    private RestServerParameters apiRestParameters;
+    private BusTopicParams apiRestParameters;
     @Setter
     private Path pathForData;
 
@@ -97,17 +101,13 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
     }
 
     @Override
-    public Request convertRequest(DecisionRequest request) {
+    public Request convertRequest(DecisionRequest request) throws ToscaPolicyConversionException {
         LOGGER.info("Converting Request {}", request);
         try {
             return StdMatchablePolicyRequest.createInstance(request);
         } catch (XacmlApplicationException e) {
-            LOGGER.error("Failed to convert DecisionRequest: {}", e);
+            throw new ToscaPolicyConversionException("Failed to convert DecisionRequest", e);
         }
-        //
-        // TODO throw exception
-        //
-        return null;
     }
 
     /**
@@ -157,6 +157,11 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
         );
     }
 
+    @Override
+    protected void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse) {
+        LOGGER.warn("scanAdvice not supported by {}", this.getClass());
+    }
+
     /**
      * scanClosestMatchObligation - scans for the obligation specifically holding policy
      * contents and their details.
@@ -169,7 +174,7 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
         //
         // Create our OnapObligation object
         //
-        OnapObligation onapObligation = new OnapObligation(obligation);
+        var onapObligation = new OnapObligation(obligation);
         //
         // All 4 *should* be there
         //
@@ -232,16 +237,16 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
     }
 
     @Override
-    public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
+    public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
         //
         // Get the TOSCA Policy Type for this policy
         //
-        Collection<ToscaPolicyType> toscaPolicyTypes = this.getPolicyTypes(toscaPolicy.getTypeIdentifier());
+        ToscaServiceTemplate toscaPolicyTypeTemplate = this.findPolicyType(toscaPolicy.getTypeIdentifier());
         //
         // If we don't have any TOSCA policy types, then we cannot know
         // which properties are matchable.
         //
-        if (toscaPolicyTypes.isEmpty()) {
+        if (toscaPolicyTypeTemplate == null) {
             throw new ToscaPolicyConversionException(
                     "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
         }
@@ -252,7 +257,7 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
         //
         // Set it as the policy ID
         //
-        PolicyType newPolicyType = new PolicyType();
+        var newPolicyType = new PolicyType();
         newPolicyType.setPolicyId(policyName);
         //
         // Optional description
@@ -270,12 +275,12 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
         // Generate the TargetType - the policy should not be evaluated
         // unless all the matchable properties it cares about are matched.
         //
-        Pair<TargetType, Integer> pairGenerated = generateTargetType(toscaPolicy.getProperties(), toscaPolicyTypes);
+        Pair<TargetType, Integer> pairGenerated = generateTargetType(toscaPolicy, toscaPolicyTypeTemplate);
         newPolicyType.setTarget(pairGenerated.getLeft());
         //
         // Now represent the policy as Json
         //
-        StandardCoder coder = new StandardCoder();
+        var coder = new StandardCoder();
         String jsonPolicy;
         try {
             jsonPolicy = coder.encode(toscaPolicy);
@@ -289,7 +294,7 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
         //
         // Now create the Permit Rule.
         //
-        RuleType rule = new RuleType();
+        var rule = new RuleType();
         rule.setDescription("Default is to PERMIT if the policy matches.");
         rule.setRuleId(policyName + ":rule");
         rule.setEffect(EffectType.PERMIT);
@@ -306,7 +311,7 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
         //
         // Log output of the policy
         //
-        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
+        try (var os = new ByteArrayOutputStream()) {
             XACMLPolicyWriter.writePolicyFile(os, newPolicyType);
             LOGGER.info("{}", os);
         } catch (IOException e) {
@@ -318,268 +323,196 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
         return newPolicyType;
     }
 
-    /**
-     * For generating target type, we scan for matchable properties
-     * and use those to build the policy.
-     *
-     * @param properties Properties section of policy
-     * @param policyTypes Collection of policy Type to find matchable metadata
-     * @return {@code Pair<TargetType, Integer>} Returns a TargetType and a Total Weight of matchables.
-     */
-    protected Pair<TargetType, Integer> generateTargetType(Map<String, Object> properties,
-            Collection<ToscaPolicyType> policyTypes) {
-        TargetType targetType = new TargetType();
-        //
-        // Iterate the properties
-        //
-        int totalWeight = 0;
-        for (Entry<String, Object> entrySet : properties.entrySet()) {
-            //
-            // Find matchable properties
-            //
-            if (isMatchable(entrySet.getKey(), policyTypes)) {
-                LOGGER.info("Found matchable property {}", entrySet.getKey());
-                int weight = generateMatchable(targetType, entrySet.getKey(), entrySet.getValue());
-                LOGGER.info("Weight is {}", weight);
-                totalWeight += weight;
-            }
+    @Override
+    public ToscaPolicyType retrievePolicyType(String derivedFrom) {
+        ToscaServiceTemplate template = this.findPolicyType(new ToscaConceptIdentifier(derivedFrom, "1.0.0"));
+        if (template == null) {
+            LOGGER.error("Could not retrieve Policy Type {}", derivedFrom);
+            return null;
         }
-        LOGGER.info("Total weight is {}", totalWeight);
-        return Pair.of(targetType, totalWeight);
+        return template.getPolicyTypes().get(derivedFrom);
     }
 
-    /**
-     * isMatchable - Iterates through available TOSCA Policy Types to determine if a property
-     * should be treated as matchable.
-     *
-     * @param propertyName Name of property
-     * @param policyTypes Collection of TOSCA Policy Types to scan
-     * @return true if matchable
-     */
-    protected boolean isMatchable(String propertyName, Collection<ToscaPolicyType> policyTypes) {
-        for (ToscaPolicyType policyType : policyTypes) {
-            for (Entry<String, ToscaProperty> propertiesEntry : policyType.getProperties().entrySet()) {
-                if (checkIsMatchableProperty(propertyName, propertiesEntry)) {
-                    return true;
-                }
-            }
-        }
-        return false;
+    @Override
+    public ToscaDataType retrieveDataType(String datatype) {
+        //
+        // Our outer class is not storing the current template being scanned
+        //
+        LOGGER.error("this retrieveDataType should not be called.");
+        return null;
     }
 
-    /**
-     * checkIsMatchableProperty - checks the policy contents for matchable field. If the metadata doesn't exist,
-     * then definitely not. If the property doesn't exist, then definitely not. Otherwise need to have a metadata
-     * section with the matchable property set to true.
-     *
-     * @param propertyName String value of property
-     * @param propertiesEntry Section of the TOSCA Policy Type where properties and metadata sections are held
-     * @return true if matchable
-     */
-    protected boolean checkIsMatchableProperty(String propertyName, Entry<String, ToscaProperty> propertiesEntry) {
-        if (! propertiesEntry.getKey().equals(propertyName)
-                || propertiesEntry.getValue().getMetadata() == null) {
-            return false;
+    private class MyMatchableCallback implements MatchableCallback {
+        private StdMatchableTranslator translator;
+        private ToscaServiceTemplate template;
+
+        public MyMatchableCallback(StdMatchableTranslator translator, ToscaServiceTemplate template) {
+            this.translator = translator;
+            this.template = template;
         }
-        for (Entry<String, String> entrySet : propertiesEntry.getValue().getMetadata().entrySet()) {
-            if ("matchable".equals(entrySet.getKey()) && "true".equals(entrySet.getValue())) {
-                return true;
+
+        @Override
+        public ToscaPolicyType retrievePolicyType(String derivedFrom) {
+            ToscaPolicyType policyType = this.template.getPolicyTypes().get(derivedFrom);
+            if (policyType != null) {
+                return policyType;
             }
+            return translator.retrievePolicyType(derivedFrom);
         }
-        return false;
-    }
 
-    /**
-     * generateMatchable - Given the object, generates list of MatchType objects and add them
-     * to the TargetType object. Returns a weight which is the number of AnyOf's generated. The
-     * weight can be used to further filter the results for "closest match".
-     *
-     * @param targetType TargetType object to add matches to
-     * @param key Property key
-     * @param value Object is the value - which can be a Collection or single Object
-     * @return int Weight of the match.
-     */
-    @SuppressWarnings("unchecked")
-    protected int generateMatchable(TargetType targetType, String key, Object value) {
-        int weight = 0;
-        if (value instanceof Collection) {
-            AnyOfType anyOf = generateMatches((Collection<Object>) value,
-                    new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + key));
-            if (! anyOf.getAllOf().isEmpty()) {
-                targetType.getAnyOf().add(anyOf);
-                weight = 1;
-            }
-        } else {
-            AnyOfType anyOf = generateMatches(Arrays.asList(value),
-                    new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + key));
-            if (! anyOf.getAllOf().isEmpty()) {
-                targetType.getAnyOf().add(anyOf);
-                weight = 1;
-            }
+        @Override
+        public ToscaDataType retrieveDataType(String datatype) {
+            return this.template.getDataTypes().get(datatype);
         }
-        return weight;
+
     }
 
     /**
-     * generateMatches - Goes through the collection of objects, creates a MatchType object
-     * for each object and associates it with the given attribute Id. Returns the AnyOfType
-     * object that contains all the generated MatchType objects.
+     * For generating target type, we scan for matchable properties
+     * and use those to build the policy.
      *
-     * @param matchables Collection of object to generate MatchType from
-     * @param attributeId Given attribute Id for each MatchType
-     * @return AnyOfType object
+     * @param properties Properties section of policy
+     * @param policyTypes Collection of policy Type to find matchable metadata
+     * @return {@code Pair<TargetType, Integer>} Returns a TargetType and a Total Weight of matchables.
      */
-    protected AnyOfType generateMatches(Collection<Object> matchables, Identifier attributeId) {
+    protected Pair<TargetType, Integer> generateTargetType(ToscaPolicy policy, ToscaServiceTemplate template) {
         //
-        // This is our outer AnyOf - which is an OR
+        // Our return object
         //
-        AnyOfType anyOf = new AnyOfType();
-        for (Object matchable : matchables) {
-            //
-            // Default to string
-            //
-            Identifier idFunction = XACML3.ID_FUNCTION_STRING_EQUAL;
-            Identifier idDatatype = XACML3.ID_DATATYPE_STRING;
-            //
-            // See if we are another datatype
+        var target = new TargetType();
+        //
+        // See if we have a matchable in the cache already
+        //
+        var matchablePolicyType = matchableCache.get(policy.getTypeIdentifier());
+        //
+        // If not found, create one
+        //
+        if (matchablePolicyType == null) {
             //
-            // We should add datetime support. But to do that we need
-            // probably more metadata to describe how that would be translated.
+            // Our callback
             //
-            if (matchable instanceof Integer) {
-                idFunction = XACML3.ID_FUNCTION_INTEGER_EQUAL;
-                idDatatype = XACML3.ID_DATATYPE_INTEGER;
-            } else if (matchable instanceof Double) {
-                idFunction = XACML3.ID_FUNCTION_DOUBLE_EQUAL;
-                idDatatype = XACML3.ID_DATATYPE_DOUBLE;
-            } else if (matchable instanceof Boolean) {
-                idFunction = XACML3.ID_FUNCTION_BOOLEAN_EQUAL;
-                idDatatype = XACML3.ID_DATATYPE_BOOLEAN;
-            }
+            var myCallback = new MyMatchableCallback(this, template);
             //
-            // Create a match for this
+            // Create the matchable
             //
-            MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
-                    idFunction,
-                    matchable.toString(),
-                    idDatatype,
-                    attributeId,
-                    XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
+            matchablePolicyType = new MatchablePolicyType(
+                    template.getPolicyTypes().get(policy.getType()), myCallback);
             //
-            // Now create an anyOf (OR)
+            // Cache it
             //
-            anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(match));
+            matchableCache.put(policy.getTypeIdentifier(), matchablePolicyType);
         }
-        return anyOf;
-    }
-
-    /**
-     * 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.
-     *
-     *
-     * @param policyTypeId Policy Type Id
-     * @return A list of PolicyTypes
-     */
-    private List<ToscaPolicyType> getPolicyTypes(ToscaPolicyTypeIdentifier policyTypeId) {
-        //
-        // Create identifier from the policy
-        //
-        ToscaPolicyTypeIdentifier typeId = new ToscaPolicyTypeIdentifier(policyTypeId);
         //
-        // Find the Policy Type
+        // Fill in the target type with potential matchables
         //
-        ToscaPolicyType policyType = findPolicyType(typeId);
-        if (policyType == null)  {
-            return Collections.emptyList();
+        try {
+            fillTargetTypeWithMatchables(target, matchablePolicyType, policy.getProperties());
+        } catch (ToscaPolicyConversionException e) {
+            LOGGER.error("Could not generate target type", e);
         }
         //
-        // Create our return object
+        // There may be a case for default policies there is no weight - need to clean
+        // up the target then else PDP will report bad policy missing AnyOf
         //
-        List<ToscaPolicyType> listTypes = new ArrayList<>();
-        listTypes.add(policyType);
+        int weight = calculateWeight(target);
+        LOGGER.debug("Weight is {} for policy {}", weight, policy.getName());
         //
-        // Look for parent policy types that could also contain matchable properties
+        // Assume the number of AllOf's is the weight for now
         //
-        ToscaPolicyType childPolicyType = policyType;
-        while (! childPolicyType.getDerivedFrom().startsWith("tosca.policies.Root")) {
-            //
-            // Create parent policy type id.
-            //
-            // We will have to assume the same version between child and the
-            // parent policy type it derives from.
-            //
-            // Or do we assume 1.0.0?
-            //
-            ToscaPolicyTypeIdentifier parentId = new ToscaPolicyTypeIdentifier(childPolicyType.getDerivedFrom(),
-                    "1.0.0");
-            //
-            // Find the policy type
-            //
-            ToscaPolicyType parentPolicyType = findPolicyType(parentId);
-            if (parentPolicyType == null) {
-                //
-                // Probably would be best to throw an exception and
-                // return nothing back.
+        return Pair.of(target, weight);
+    }
+
+    @SuppressWarnings("unchecked")
+    protected void fillTargetTypeWithMatchables(TargetType target, MatchablePolicyType matchablePolicyType,
+            Map<String, Object> properties) throws ToscaPolicyConversionException {
+        for (Entry<String, Object> entrySet : properties.entrySet()) {
+            String propertyName = entrySet.getKey();
+            Object propertyValue = entrySet.getValue();
+            MatchableProperty matchable = matchablePolicyType.get(propertyName);
+            if (matchable != null) {
                 //
-                // But instead we will log a warning
+                // Construct attribute id
                 //
-                LOGGER.warn("Missing parent policy type - proceeding anyway {}", parentId);
+                Identifier id = new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + propertyName);
                 //
-                // Break the loop
+                // Depending on what type it is, add it into the target
                 //
-                break;
+                ToscaPolicyTranslatorUtils.buildAndAppendTarget(target,
+                        matchable.getType().generate(propertyValue, id));
+
+                continue;
             }
             //
-            // Great save it
-            //
-            listTypes.add(parentPolicyType);
-            //
-            // Move to the next parent
+            // Here is the special case where we look for a Collection of values that may
+            // contain potential matchables
             //
-            childPolicyType = parentPolicyType;
+            if (propertyValue instanceof List) {
+                for (Object listValue : ((List<?>) propertyValue)) {
+                    if (listValue instanceof Map) {
+                        fillTargetTypeWithMatchables(target, matchablePolicyType, (Map<String, Object>) listValue);
+                    }
+                }
+            } else if (propertyValue instanceof Map) {
+                fillTargetTypeWithMatchables(target, matchablePolicyType, (Map<String, Object>) propertyValue);
+            }
+        }
+    }
+
+    protected int calculateWeight(TargetType target) {
+        var weight = 0;
+        for (AnyOfType anyOf : target.getAnyOf()) {
+            for (AllOfType allOf : anyOf.getAllOf()) {
+                weight += allOf.getMatch().size();
+            }
         }
-        return listTypes;
+
+        return weight;
     }
 
     /**
-     * findPolicyType - given the ToscaPolicyTypeIdentifier, finds it in memory, or
+     * findPolicyType - given the ToscaConceptIdentifier, finds it in memory, or
      * then tries to find it either locally on disk or pull it from the Policy
      * Lifecycle API the given TOSCA Policy Type.
      *
-     * @param policyTypeId ToscaPolicyTypeIdentifier to find
+     * @param policyTypeId ToscaConceptIdentifier to find
      * @return ToscaPolicyType object. Can be null if failure.
      */
-    private ToscaPolicyType findPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
+    private ToscaServiceTemplate findPolicyType(ToscaConceptIdentifier policyTypeId) {
         //
         // Is it loaded in memory?
         //
-        ToscaPolicyType policyType = this.matchablePolicyTypes.get(policyTypeId);
-        if (policyType == null)  {
+        ToscaServiceTemplate policyTemplate = this.matchablePolicyTypes.get(policyTypeId);
+        if (policyTemplate == null)  {
             //
             // Load the policy
             //
-            policyType = this.loadPolicyType(policyTypeId);
+            policyTemplate = this.loadPolicyType(policyTypeId);
+            //
+            // Save it
+            //
+            if (policyTemplate != null) {
+                this.matchablePolicyTypes.put(policyTypeId, policyTemplate);
+            }
         }
         //
         // Yep return it
         //
-        return policyType;
+        return policyTemplate;
     }
 
     /**
-     * loadPolicyType - Tries to load the given ToscaPolicyTypeIdentifier from local
+     * loadPolicyType - Tries to load the given ToscaConceptIdentifier from local
      * storage. If it does not exist, will then attempt to pull from Policy Lifecycle
      * API.
      *
-     * @param policyTypeId ToscaPolicyTypeIdentifier input
+     * @param policyTypeId ToscaConceptIdentifier input
      * @return ToscaPolicyType object. Null if failure.
      */
-    private ToscaPolicyType loadPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
+    private ToscaServiceTemplate loadPolicyType(ToscaConceptIdentifier policyTypeId) {
         //
         // Construct what the file name should be
         //
-        Path policyTypePath = this.constructLocalFilePath(policyTypeId);
+        var policyTypePath = this.constructLocalFilePath(policyTypeId);
         //
         // See if it exists
         //
@@ -605,34 +538,17 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
         //
         LOGGER.info("Read in local policy type {}", policyTypePath.toAbsolutePath());
         try {
-            ToscaServiceTemplate serviceTemplate = standardYamlCoder.decode(new String(bytes, StandardCharsets.UTF_8),
-                    ToscaServiceTemplate.class);
-            JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
-            jtst.fromAuthorative(serviceTemplate);
-            ToscaServiceTemplate completedJtst = jtst.toAuthorative();
             //
-            // Search for our Policy Type, there really only should be one but
-            // this is returned as a map.
+            // Decode the template
             //
-            for ( Entry<String, ToscaPolicyType> entrySet : completedJtst.getPolicyTypes().entrySet()) {
-                ToscaPolicyType entryPolicyType = entrySet.getValue();
-                if (policyTypeId.getName().equals(entryPolicyType.getName())
-                        && policyTypeId.getVersion().equals(entryPolicyType.getVersion())) {
-                    LOGGER.info("Found existing local policy type {} {}", entryPolicyType.getName(),
-                            entryPolicyType.getVersion());
-                    //
-                    // Just simply return the policy type right here
-                    //
-                    return entryPolicyType;
-                } else {
-                    LOGGER.warn("local policy type contains different name version {} {}", entryPolicyType.getName(),
-                            entryPolicyType.getVersion());
-                }
-            }
+            ToscaServiceTemplate template = standardYamlCoder.decode(new String(bytes, StandardCharsets.UTF_8),
+                    ToscaServiceTemplate.class);
             //
-            // This would be an error, if the file stored does not match what its supposed to be
+            // Ensure all the fields are setup correctly
             //
-            LOGGER.error("Existing policy type file does not contain right name and version");
+            var jtst = new JpaToscaServiceTemplate();
+            jtst.fromAuthorative(template);
+            return jtst.toAuthorative();
         } catch (CoderException e) {
             LOGGER.error("Failed to decode tosca template for {}", policyTypePath, e);
         }
@@ -644,49 +560,50 @@ public class StdMatchableTranslator  extends StdBaseTranslator {
     }
 
     /**
-     * pullPolicyType - pulls the given ToscaPolicyTypeIdentifier from the Policy Lifecycle API.
+     * pullPolicyType - pulls the given ToscaConceptIdentifier from the Policy Lifecycle API.
      * If successful, will store it locally given the policyTypePath.
      *
-     * @param policyTypeId ToscaPolicyTypeIdentifier
+     * @param policyTypeId ToscaConceptIdentifier
      * @param policyTypePath Path object to store locally
      * @return ToscaPolicyType object. Null if failure.
      */
-    private synchronized ToscaPolicyType pullPolicyType(ToscaPolicyTypeIdentifier policyTypeId, Path policyTypePath) {
+    private synchronized ToscaServiceTemplate pullPolicyType(ToscaConceptIdentifier policyTypeId,
+            Path policyTypePath) {
         //
         // This is what we return
         //
-        ToscaPolicyType policyType = null;
+        ToscaServiceTemplate policyTemplate = null;
         try {
-            PolicyApiCaller api = new PolicyApiCaller(this.apiRestParameters);
+            var api = new PolicyApiCaller(this.apiRestParameters);
 
-            policyType = api.getPolicyType(policyTypeId);
+            policyTemplate = api.getPolicyType(policyTypeId);
         } catch (PolicyApiException e) {
             LOGGER.error("Failed to make API call", e);
-            LOGGER.error("parameters: {} ", this.apiRestParameters);
             return null;
         }
+        LOGGER.info("Successfully pulled {}", policyTypeId);
         //
         // Store it locally
         //
         try {
-            standardYamlCoder.encode(policyTypePath.toFile(), policyType);
+            standardYamlCoder.encode(policyTypePath.toFile(), policyTemplate);
         } catch (CoderException e) {
             LOGGER.error("Failed to store {} locally to {}", policyTypeId, policyTypePath, e);
         }
         //
         // Done return the policy type
         //
-        return policyType;
+        return policyTemplate;
     }
 
     /**
      * constructLocalFilePath - common method to ensure the name of the local file for the
      * policy type is the same.
      *
-     * @param policyTypeId ToscaPolicyTypeIdentifier
+     * @param policyTypeId ToscaConceptIdentifier
      * @return Path object
      */
-    private Path constructLocalFilePath(ToscaPolicyTypeIdentifier policyTypeId) {
+    private Path constructLocalFilePath(ToscaConceptIdentifier policyTypeId) {
         return Paths.get(this.pathForData.toAbsolutePath().toString(), policyTypeId.getName() + "-"
                 + policyTypeId.getVersion() + ".yaml");
     }