addb0df394fbe9b0001fa70a7bcfd319f98b9296
[policy/xacml-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pdp.xacml.application.common.std;
24
25 import com.att.research.xacml.api.Identifier;
26 import com.att.research.xacml.api.Obligation;
27 import com.att.research.xacml.api.Request;
28 import com.att.research.xacml.api.XACML3;
29 import com.att.research.xacml.std.IdentifierImpl;
30 import com.att.research.xacml.util.XACMLPolicyWriter;
31 import java.io.ByteArrayOutputStream;
32 import java.io.IOException;
33 import java.nio.charset.StandardCharsets;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.nio.file.Paths;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.LinkedHashMap;
43 import java.util.LinkedList;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Map.Entry;
47 import lombok.Setter;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
54 import org.apache.commons.lang3.tuple.Pair;
55 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
56 import org.onap.policy.common.utils.coder.CoderException;
57 import org.onap.policy.common.utils.coder.StandardCoder;
58 import org.onap.policy.common.utils.coder.StandardYamlCoder;
59 import org.onap.policy.models.decisions.concepts.DecisionRequest;
60 import org.onap.policy.models.decisions.concepts.DecisionResponse;
61 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
62 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
63 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
64 import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
65 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
66 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
67 import org.onap.policy.pdp.xacml.application.common.OnapObligation;
68 import org.onap.policy.pdp.xacml.application.common.PolicyApiCaller;
69 import org.onap.policy.pdp.xacml.application.common.PolicyApiException;
70 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
71 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
72 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
73 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77 /**
78  * This standard matchable translator uses Policy Types that contain "matchable" field in order
79  * to translate policies.
80  *
81  * @author pameladragosh
82  *
83  */
84 public class StdMatchableTranslator  extends StdBaseTranslator {
85
86     private static final Logger LOGGER = LoggerFactory.getLogger(StdMatchableTranslator.class);
87     private static final StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
88
89     private final Map<ToscaPolicyTypeIdentifier, ToscaPolicyType> matchablePolicyTypes = new HashMap<>();
90     @Setter
91     private RestServerParameters apiRestParameters;
92     @Setter
93     private Path pathForData;
94
95     public StdMatchableTranslator() {
96         super();
97     }
98
99     @Override
100     public Request convertRequest(DecisionRequest request) {
101         LOGGER.info("Converting Request {}", request);
102         try {
103             return StdMatchablePolicyRequest.createInstance(request);
104         } catch (XacmlApplicationException e) {
105             LOGGER.error("Failed to convert DecisionRequest: {}", e);
106         }
107         //
108         // TODO throw exception
109         //
110         return null;
111     }
112
113     /**
114      * scanObligations - scans the list of obligations and make appropriate method calls to process
115      * obligations.
116      *
117      * @param obligations Collection of obligation objects
118      * @param decisionResponse DecisionResponse object used to store any results from obligations.
119      */
120     @Override
121     protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
122         //
123         // Implementing a crude "closest match" on the results, which means we will strip out
124         // any policies that has the lower weight than any of the others.
125         //
126         // Most likely these are "default" policies with a weight of zero, but not always.
127         //
128         // It is possible to have multiple policies with an equal weight, that is desired.
129         //
130         // So we need to track each policy type separately and the weights for each policy.
131         //
132         // policy-type -> weight -> List({policy-id, policy-content}, {policy-id, policy-content})
133         //
134         Map<String, Map<Integer, List<Pair<String, Map<String, Object>>>>> closestMatches = new LinkedHashMap<>();
135         //
136         // Now scan the list of obligations
137         //
138         for (Obligation obligation : obligations) {
139             Identifier obligationId = obligation.getId();
140             LOGGER.info("Obligation: {}", obligationId);
141             if (ToscaDictionary.ID_OBLIGATION_REST_BODY.equals(obligationId)) {
142                 scanClosestMatchObligation(closestMatches, obligation);
143             } else {
144                 LOGGER.warn("Unsupported Obligation Id {}", obligation.getId());
145             }
146         }
147         //
148         // Now add all the policies to the DecisionResponse
149         //
150         closestMatches.forEach((thePolicyType, weightMap) ->
151             weightMap.forEach((weight, policies) ->
152                 policies.forEach(policy -> {
153                     LOGGER.info("Policy {}", policy);
154                     decisionResponse.getPolicies().put(policy.getLeft(), policy.getRight());
155                 })
156             )
157         );
158     }
159
160     /**
161      * scanClosestMatchObligation - scans for the obligation specifically holding policy
162      * contents and their details.
163      *
164      * @param closestMatches Map holding the current set of highest weight policy types
165      * @param Obligation Obligation object
166      */
167     protected void scanClosestMatchObligation(
168             Map<String, Map<Integer, List<Pair<String, Map<String, Object>>>>> closestMatches, Obligation obligation) {
169         //
170         // Create our OnapObligation object
171         //
172         OnapObligation onapObligation = new OnapObligation(obligation);
173         //
174         // All 4 *should* be there
175         //
176         if (onapObligation.getPolicyId() == null || onapObligation.getPolicyContent() == null
177                 || onapObligation.getPolicyType() == null || onapObligation.getWeight() == null) {
178             LOGGER.error("Missing an expected attribute in obligation.");
179             return;
180         }
181         //
182         // Save the values
183         //
184         String policyId = onapObligation.getPolicyId();
185         String policyType = onapObligation.getPolicyType();
186         Map<String, Object> policyContent = onapObligation.getPolicyContentAsMap();
187         int policyWeight = onapObligation.getWeight();
188         //
189         // If the Policy Type exists, get the weight map.
190         //
191         Map<Integer, List<Pair<String, Map<String, Object>>>> weightMap = closestMatches.get(policyType);
192         if (weightMap != null) {
193             //
194             // Only need to check first one - as we will ensure there is only one weight
195             //
196             Entry<Integer, List<Pair<String, Map<String, Object>>>> firstEntry =
197                     weightMap.entrySet().iterator().next();
198             if (policyWeight < firstEntry.getKey()) {
199                 //
200                 // Existing policies have a greater weight, so we will not add it
201                 //
202                 LOGGER.info("{} is lesser weight {} than current policies, will not return it", policyWeight,
203                         firstEntry.getKey());
204             } else if (firstEntry.getKey().equals(policyWeight)) {
205                 //
206                 // Same weight - we will add it
207                 //
208                 LOGGER.info("Same weight {}, adding policy", policyWeight);
209                 firstEntry.getValue().add(Pair.of(policyId, policyContent));
210             } else {
211                 //
212                 // The weight is greater, so we need to remove the other policies
213                 // and point to this one.
214                 //
215                 LOGGER.info("New policy has greater weight {}, replacing {}", policyWeight, firstEntry.getKey());
216                 List<Pair<String, Map<String, Object>>> listPolicies = new LinkedList<>();
217                 listPolicies.add(Pair.of(policyId, policyContent));
218                 weightMap.clear();
219                 weightMap.put(policyWeight, listPolicies);
220             }
221         } else {
222             //
223             // Create a new entry
224             //
225             LOGGER.info("New entry {} weight {}", policyType, policyWeight);
226             List<Pair<String, Map<String, Object>>> listPolicies = new LinkedList<>();
227             listPolicies.add(Pair.of(policyId, policyContent));
228             Map<Integer, List<Pair<String, Map<String, Object>>>> newWeightMap = new LinkedHashMap<>();
229             newWeightMap.put(policyWeight, listPolicies);
230             closestMatches.put(policyType, newWeightMap);
231         }
232     }
233
234     @Override
235     public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
236         //
237         // Get the TOSCA Policy Type for this policy
238         //
239         Collection<ToscaPolicyType> toscaPolicyTypes = this.getPolicyTypes(toscaPolicy.getTypeIdentifier());
240         //
241         // If we don't have any TOSCA policy types, then we cannot know
242         // which properties are matchable.
243         //
244         if (toscaPolicyTypes.isEmpty()) {
245             throw new ToscaPolicyConversionException(
246                     "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
247         }
248         //
249         // Policy name should be at the root
250         //
251         String policyName = toscaPolicy.getMetadata().get(POLICY_ID);
252         //
253         // Set it as the policy ID
254         //
255         PolicyType newPolicyType = new PolicyType();
256         newPolicyType.setPolicyId(policyName);
257         //
258         // Optional description
259         //
260         newPolicyType.setDescription(toscaPolicy.getDescription());
261         //
262         // There should be a metadata section
263         //
264         fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
265         //
266         // Set the combining rule
267         //
268         newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
269         //
270         // Generate the TargetType - the policy should not be evaluated
271         // unless all the matchable properties it cares about are matched.
272         //
273         Pair<TargetType, Integer> pairGenerated = generateTargetType(toscaPolicy.getProperties(), toscaPolicyTypes);
274         newPolicyType.setTarget(pairGenerated.getLeft());
275         //
276         // Now represent the policy as Json
277         //
278         StandardCoder coder = new StandardCoder();
279         String jsonPolicy;
280         try {
281             jsonPolicy = coder.encode(toscaPolicy);
282         } catch (CoderException e) {
283             throw new ToscaPolicyConversionException("Failed to encode policy to json", e);
284         }
285         //
286         // Add it as an obligation
287         //
288         addObligation(newPolicyType, policyName, jsonPolicy, pairGenerated.getRight(), toscaPolicy.getType());
289         //
290         // Now create the Permit Rule.
291         //
292         RuleType rule = new RuleType();
293         rule.setDescription("Default is to PERMIT if the policy matches.");
294         rule.setRuleId(policyName + ":rule");
295         rule.setEffect(EffectType.PERMIT);
296         rule.setTarget(new TargetType());
297         //
298         // The rule contains the Condition which adds logic for
299         // optional policy-type filtering.
300         //
301         rule.setCondition(generateConditionForPolicyType(toscaPolicy.getType()));
302         //
303         // Add the rule to the policy
304         //
305         newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
306         //
307         // Log output of the policy
308         //
309         try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
310             XACMLPolicyWriter.writePolicyFile(os, newPolicyType);
311             LOGGER.info("{}", os);
312         } catch (IOException e) {
313             LOGGER.error("Failed to create byte array stream", e);
314         }
315         //
316         // Done
317         //
318         return newPolicyType;
319     }
320
321     /**
322      * For generating target type, we scan for matchable properties
323      * and use those to build the policy.
324      *
325      * @param properties Properties section of policy
326      * @param policyTypes Collection of policy Type to find matchable metadata
327      * @return {@code Pair<TargetType, Integer>} Returns a TargetType and a Total Weight of matchables.
328      */
329     protected Pair<TargetType, Integer> generateTargetType(Map<String, Object> properties,
330             Collection<ToscaPolicyType> policyTypes) {
331         TargetType targetType = new TargetType();
332         //
333         // Iterate the properties
334         //
335         int totalWeight = 0;
336         for (Entry<String, Object> entrySet : properties.entrySet()) {
337             //
338             // Find matchable properties
339             //
340             if (isMatchable(entrySet.getKey(), policyTypes)) {
341                 LOGGER.info("Found matchable property {}", entrySet.getKey());
342                 int weight = generateMatchable(targetType, entrySet.getKey(), entrySet.getValue());
343                 LOGGER.info("Weight is {}", weight);
344                 totalWeight += weight;
345             }
346         }
347         LOGGER.info("Total weight is {}", totalWeight);
348         return Pair.of(targetType, totalWeight);
349     }
350
351     /**
352      * isMatchable - Iterates through available TOSCA Policy Types to determine if a property
353      * should be treated as matchable.
354      *
355      * @param propertyName Name of property
356      * @param policyTypes Collection of TOSCA Policy Types to scan
357      * @return true if matchable
358      */
359     protected boolean isMatchable(String propertyName, Collection<ToscaPolicyType> policyTypes) {
360         for (ToscaPolicyType policyType : policyTypes) {
361             for (Entry<String, ToscaProperty> propertiesEntry : policyType.getProperties().entrySet()) {
362                 if (checkIsMatchableProperty(propertyName, propertiesEntry)) {
363                     return true;
364                 }
365             }
366         }
367         return false;
368     }
369
370     /**
371      * checkIsMatchableProperty - checks the policy contents for matchable field. If the metadata doesn't exist,
372      * then definitely not. If the property doesn't exist, then definitely not. Otherwise need to have a metadata
373      * section with the matchable property set to true.
374      *
375      * @param propertyName String value of property
376      * @param propertiesEntry Section of the TOSCA Policy Type where properties and metadata sections are held
377      * @return true if matchable
378      */
379     protected boolean checkIsMatchableProperty(String propertyName, Entry<String, ToscaProperty> propertiesEntry) {
380         if (! propertiesEntry.getKey().equals(propertyName)
381                 || propertiesEntry.getValue().getMetadata() == null) {
382             return false;
383         }
384         for (Entry<String, String> entrySet : propertiesEntry.getValue().getMetadata().entrySet()) {
385             if ("matchable".equals(entrySet.getKey()) && "true".equals(entrySet.getValue())) {
386                 return true;
387             }
388         }
389         return false;
390     }
391
392     /**
393      * generateMatchable - Given the object, generates list of MatchType objects and add them
394      * to the TargetType object. Returns a weight which is the number of AnyOf's generated. The
395      * weight can be used to further filter the results for "closest match".
396      *
397      * @param targetType TargetType object to add matches to
398      * @param key Property key
399      * @param value Object is the value - which can be a Collection or single Object
400      * @return int Weight of the match.
401      */
402     @SuppressWarnings("unchecked")
403     protected int generateMatchable(TargetType targetType, String key, Object value) {
404         int weight = 0;
405         if (value instanceof Collection) {
406             AnyOfType anyOf = generateMatches((Collection<Object>) value,
407                     new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + key));
408             if (! anyOf.getAllOf().isEmpty()) {
409                 targetType.getAnyOf().add(anyOf);
410                 weight = 1;
411             }
412         } else {
413             AnyOfType anyOf = generateMatches(Arrays.asList(value),
414                     new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + key));
415             if (! anyOf.getAllOf().isEmpty()) {
416                 targetType.getAnyOf().add(anyOf);
417                 weight = 1;
418             }
419         }
420         return weight;
421     }
422
423     /**
424      * generateMatches - Goes through the collection of objects, creates a MatchType object
425      * for each object and associates it with the given attribute Id. Returns the AnyOfType
426      * object that contains all the generated MatchType objects.
427      *
428      * @param matchables Collection of object to generate MatchType from
429      * @param attributeId Given attribute Id for each MatchType
430      * @return AnyOfType object
431      */
432     protected AnyOfType generateMatches(Collection<Object> matchables, Identifier attributeId) {
433         //
434         // This is our outer AnyOf - which is an OR
435         //
436         AnyOfType anyOf = new AnyOfType();
437         for (Object matchable : matchables) {
438             //
439             // Default to string
440             //
441             Identifier idFunction = XACML3.ID_FUNCTION_STRING_EQUAL;
442             Identifier idDatatype = XACML3.ID_DATATYPE_STRING;
443             //
444             // See if we are another datatype
445             //
446             // We should add datetime support. But to do that we need
447             // probably more metadata to describe how that would be translated.
448             //
449             if (matchable instanceof Integer) {
450                 idFunction = XACML3.ID_FUNCTION_INTEGER_EQUAL;
451                 idDatatype = XACML3.ID_DATATYPE_INTEGER;
452             } else if (matchable instanceof Double) {
453                 idFunction = XACML3.ID_FUNCTION_DOUBLE_EQUAL;
454                 idDatatype = XACML3.ID_DATATYPE_DOUBLE;
455             } else if (matchable instanceof Boolean) {
456                 idFunction = XACML3.ID_FUNCTION_BOOLEAN_EQUAL;
457                 idDatatype = XACML3.ID_DATATYPE_BOOLEAN;
458             }
459             //
460             // Create a match for this
461             //
462             MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
463                     idFunction,
464                     matchable.toString(),
465                     idDatatype,
466                     attributeId,
467                     XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
468             //
469             // Now create an anyOf (OR)
470             //
471             anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(match));
472         }
473         return anyOf;
474     }
475
476     /**
477      * Get Policy Type definitions. This could be previously loaded, or could be
478      * stored in application path, or may need to be pulled from the API.
479      *
480      *
481      * @param policyTypeId Policy Type Id
482      * @return A list of PolicyTypes
483      */
484     private List<ToscaPolicyType> getPolicyTypes(ToscaPolicyTypeIdentifier policyTypeId) {
485         //
486         // Create identifier from the policy
487         //
488         ToscaPolicyTypeIdentifier typeId = new ToscaPolicyTypeIdentifier(policyTypeId);
489         //
490         // Find the Policy Type
491         //
492         ToscaPolicyType policyType = findPolicyType(typeId);
493         if (policyType == null)  {
494             return Collections.emptyList();
495         }
496         //
497         // Create our return object
498         //
499         List<ToscaPolicyType> listTypes = new ArrayList<>();
500         listTypes.add(policyType);
501         //
502         // Look for parent policy types that could also contain matchable properties
503         //
504         ToscaPolicyType childPolicyType = policyType;
505         while (! childPolicyType.getDerivedFrom().startsWith("tosca.policies.Root")) {
506             //
507             // Create parent policy type id.
508             //
509             // We will have to assume the same version between child and the
510             // parent policy type it derives from.
511             //
512             // Or do we assume 1.0.0?
513             //
514             ToscaPolicyTypeIdentifier parentId = new ToscaPolicyTypeIdentifier(childPolicyType.getDerivedFrom(),
515                     "1.0.0");
516             //
517             // Find the policy type
518             //
519             ToscaPolicyType parentPolicyType = findPolicyType(parentId);
520             if (parentPolicyType == null) {
521                 //
522                 // Probably would be best to throw an exception and
523                 // return nothing back.
524                 //
525                 // But instead we will log a warning
526                 //
527                 LOGGER.warn("Missing parent policy type - proceeding anyway {}", parentId);
528                 //
529                 // Break the loop
530                 //
531                 break;
532             }
533             //
534             // Great save it
535             //
536             listTypes.add(parentPolicyType);
537             //
538             // Move to the next parent
539             //
540             childPolicyType = parentPolicyType;
541         }
542         return listTypes;
543     }
544
545     /**
546      * findPolicyType - given the ToscaPolicyTypeIdentifier, finds it in memory, or
547      * then tries to find it either locally on disk or pull it from the Policy
548      * Lifecycle API the given TOSCA Policy Type.
549      *
550      * @param policyTypeId ToscaPolicyTypeIdentifier to find
551      * @return ToscaPolicyType object. Can be null if failure.
552      */
553     private ToscaPolicyType findPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
554         //
555         // Is it loaded in memory?
556         //
557         ToscaPolicyType policyType = this.matchablePolicyTypes.get(policyTypeId);
558         if (policyType == null)  {
559             //
560             // Load the policy
561             //
562             policyType = this.loadPolicyType(policyTypeId);
563         }
564         //
565         // Yep return it
566         //
567         return policyType;
568     }
569
570     /**
571      * loadPolicyType - Tries to load the given ToscaPolicyTypeIdentifier from local
572      * storage. If it does not exist, will then attempt to pull from Policy Lifecycle
573      * API.
574      *
575      * @param policyTypeId ToscaPolicyTypeIdentifier input
576      * @return ToscaPolicyType object. Null if failure.
577      */
578     private ToscaPolicyType loadPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
579         //
580         // Construct what the file name should be
581         //
582         Path policyTypePath = this.constructLocalFilePath(policyTypeId);
583         //
584         // See if it exists
585         //
586         byte[] bytes;
587         try {
588             //
589             // If it exists locally, read the bytes in
590             //
591             bytes = Files.readAllBytes(policyTypePath);
592         } catch (IOException e) {
593             //
594             // Does not exist locally, so let's GET it from the policy api
595             //
596             LOGGER.error("PolicyType not found in data area yet {}", policyTypePath, e);
597             //
598             // So let's pull it from API REST call and save it locally
599             //
600             return this.pullPolicyType(policyTypeId, policyTypePath);
601         }
602         //
603         // Success - we have read locally the policy type. Now bring it into our
604         // return object.
605         //
606         LOGGER.info("Read in local policy type {}", policyTypePath.toAbsolutePath());
607         try {
608             ToscaServiceTemplate serviceTemplate = standardYamlCoder.decode(new String(bytes, StandardCharsets.UTF_8),
609                     ToscaServiceTemplate.class);
610             JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
611             jtst.fromAuthorative(serviceTemplate);
612             ToscaServiceTemplate completedJtst = jtst.toAuthorative();
613             //
614             // Search for our Policy Type, there really only should be one but
615             // this is returned as a map.
616             //
617             for ( Entry<String, ToscaPolicyType> entrySet : completedJtst.getPolicyTypes().entrySet()) {
618                 ToscaPolicyType entryPolicyType = entrySet.getValue();
619                 if (policyTypeId.getName().equals(entryPolicyType.getName())
620                         && policyTypeId.getVersion().equals(entryPolicyType.getVersion())) {
621                     LOGGER.info("Found existing local policy type {} {}", entryPolicyType.getName(),
622                             entryPolicyType.getVersion());
623                     //
624                     // Just simply return the policy type right here
625                     //
626                     return entryPolicyType;
627                 } else {
628                     LOGGER.warn("local policy type contains different name version {} {}", entryPolicyType.getName(),
629                             entryPolicyType.getVersion());
630                 }
631             }
632             //
633             // This would be an error, if the file stored does not match what its supposed to be
634             //
635             LOGGER.error("Existing policy type file does not contain right name and version");
636         } catch (CoderException e) {
637             LOGGER.error("Failed to decode tosca template for {}", policyTypePath, e);
638         }
639         //
640         // Hopefully we never get here
641         //
642         LOGGER.error("Failed to find/load policy type {}", policyTypeId);
643         return null;
644     }
645
646     /**
647      * pullPolicyType - pulls the given ToscaPolicyTypeIdentifier from the Policy Lifecycle API.
648      * If successful, will store it locally given the policyTypePath.
649      *
650      * @param policyTypeId ToscaPolicyTypeIdentifier
651      * @param policyTypePath Path object to store locally
652      * @return ToscaPolicyType object. Null if failure.
653      */
654     private synchronized ToscaPolicyType pullPolicyType(ToscaPolicyTypeIdentifier policyTypeId, Path policyTypePath) {
655         //
656         // This is what we return
657         //
658         ToscaPolicyType policyType = null;
659         try {
660             PolicyApiCaller api = new PolicyApiCaller(this.apiRestParameters);
661
662             policyType = api.getPolicyType(policyTypeId);
663         } catch (PolicyApiException e) {
664             LOGGER.error("Failed to make API call", e);
665             LOGGER.error("parameters: {} ", this.apiRestParameters);
666             return null;
667         }
668         //
669         // Store it locally
670         //
671         try {
672             standardYamlCoder.encode(policyTypePath.toFile(), policyType);
673         } catch (CoderException e) {
674             LOGGER.error("Failed to store {} locally to {}", policyTypeId, policyTypePath, e);
675         }
676         //
677         // Done return the policy type
678         //
679         return policyType;
680     }
681
682     /**
683      * constructLocalFilePath - common method to ensure the name of the local file for the
684      * policy type is the same.
685      *
686      * @param policyTypeId ToscaPolicyTypeIdentifier
687      * @return Path object
688      */
689     private Path constructLocalFilePath(ToscaPolicyTypeIdentifier policyTypeId) {
690         return Paths.get(this.pathForData.toAbsolutePath().toString(), policyTypeId.getName() + "-"
691                 + policyTypeId.getVersion() + ".yaml");
692     }
693 }